« WeWantWorkBoston.com | Main | SimpleBlogService fixes. »

Interfaces and when what appears private is actually public.

If you’ve ever looked into the implementation details of CollectionBase, especially the IEnumerator support, or wondered why ICloneable appears to force you to return an object from Clone, you probably discovered Explicit interface member implementations which allow you to define a weakly typed method to satisfy the interface while also defining a strongly typed method.

I’m one of those people who doesn’t type “private” in front of every class field and method since I know it’s the default access modifier.

So when I see something like the following I assume it’s a private method, but it’s actually public in the sense that anyone with a reference to one of my objects can call it.

int IList.Add(object card) { return list.Add((Card) card); } // This method is public

 

Anyone can call the IList.Add method on one of my objects by using a cast to get at the IList interface. E.g.

CardCollection cards = new CardCollection();

((IList)cards).Add(someObject); // invokes what you may have thought was a private method.

 

If you consider that all interface methods must have public access, this makes sense and is desirable. I found it confusing that it is a compile error to put a “public” access modifier on an explicit interface method implementation. The default access modifier is private, and yet in this case the behavior is public.

If you simply implement a method that matches the signature of an interface method without using the explicit interface member syntax, you must explicitly declare it “public”.

 

 

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)