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.

wattostudios
  • 8,666
  • 13
  • 43
  • 57
Dervin Thunk
  • 19,515
  • 28
  • 127
  • 217

3 Answers3

6

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
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 1
    `internal`/`Friend` on the other hand might make sense, theoretically. Not that I've ever needed, though. – Konrad Rudolph Jun 24 '09 at 14:38
  • 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 Jun 24 '09 at 14:38
  • You could have multiple interfaces with different set of your methods and hand them to various clients. – akarnokd Jun 24 '09 at 14:43
  • @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 Jun 24 '09 at 14:49
5

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
  • 55,384
  • 17
  • 145
  • 179
4

In C# all members of an interface must be public, therefore it will not allow you to add any visibility modifiers to the member declarations. 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 which states that you will provide all of the functionlity specified in the interface definition. 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).

Doctor Jones
  • 21,196
  • 13
  • 77
  • 99
  • 1
    +1 for the explanation of why interface methods are always public. In fact, you should get a few more. Hint hint, people! – Randolpho Jun 24 '09 at 14:44