views:

308

answers:

3

Another translation question, this may be more theoretical, but I am curious as to the design choice. SFNQ:

Why does C# not allow controlling for controlling access to methods in interfaces like Java does? For example, in a C# interface:

   public void Visit(Axiom axiom);

Thank you.

+5  A: 

In both C# and Java, all methods on an interface are public.

In Java, the public keyword is allowed, likely to save on parsing rules. In C#, the public keyword was considered redundant and was removed from interface declarations altogether.

Randolpho
Correction: In Java, the public keyword is optional and will be ignored if present.
Michael Myers
Not just redundant, it's actually a compiler error to put it there. A constant source of frustration for me, coming from Java to C#.
Eric Petroelje
Thanks. But it is more than "redundant", the compiler will yell at me if I try putting it in.
Dervin Thunk
@mmyers: good point; edited.
Randolpho
@Eric Petroejle @Dervin Thunk: I realize that wasn't very clear. Edited for clarity.
Randolpho
+6  A: 

In C#, and .Net in general, all methods on an interface are public by default. There is no way to restrict their access.

Consider the alternative, what would it mean to have a protected member on an interface? How would you establish the access rules to allow or disallow a caller of an interface access to the particular method? (I mean protected in the C# sense, not the java one).

Even better, what would private mean?

JaredPar
`internal`/`Friend` on the other hand might make sense, theoretically. Not that I've ever needed, though.
Konrad Rudolph
While those options don't make sense, it would sometimes be nice to allow an internal implementation of an internal interface, without resorting to explicit interface implementation.
Jon Skeet
You could have multiple interfaces with different set of your methods and hand them to various clients.
kd304
@Jon Skeet: If the interface is internal, why not mark it internal? The methods may be public, but the use of the interface would only be internal. And if you explicitly implement the internal interface, your explicit implementation will be, in effect, internal.
Randolpho
+4  A: 

In C# all methods in an interface must be public, therefore it will not allow you to provide any visibility modifiers to the declaration. The public keyword is therefore redundant and not needed (infact if you include it you'll get a compiler error).

An interface is a contract that states you will provide all of the functionlity specified in the interface. If you were allowed to have private members in an interface you would not be exposing that functionality (and you would therefore violate the contract).

DoctaJonez
+1 for the explanation of why interface methods are always public. In fact, you should get a few more. Hint hint, people!
Randolpho
Thanks very much Randolpho :-)
DoctaJonez