Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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?

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top