Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must an C# interface method implemented in a class be public?

I have a class which inherits an interface. An interface member method is implemented in my class without an access modifier (so, by default it's private ) .

I am getting the error "cannot implement an interface member because it is not public".

Why it is not allowed? Can't I override the accessibility?

like image 589
Kuntady Nithesh Avatar asked Aug 30 '11 04:08

Kuntady Nithesh


People also ask

Is it worth it learning C?

Is Learning C Worth It? Learning C is worth it. It is hard to avoid C because it is used to write OS kernels, databases, compilers, and many other applications. Knowledge of C will be required to debug or improve them.

Why C language is called C?

After language 'B', Dennis Ritchie came up with another language which was based upon 'B'. As in alphabets B is followed by C and hence he called this language as 'C'.


1 Answers

Here's an example of why it doesn't make sense to be able to override the visibility:

interface someI {     void doYourWork(); } public class A : someI {     public void doYourWork()     {         //...     } }  public class B : someI {     private void doYourWork()     {         //...     } } void Main() {     List<someI> workers = getWorkers();     foreach(var worker in workers)         worker.doYourWork(); } 

What happens when your worker is of type B? You're calling a method as if it were public, but it's a private method. If you want this functionality, then it's not really a private method is it?

If you only want it to be public when referenced through your interface, then you can define it as such:

public class B : someI {     void someI.doYourWork()     {         //...     } } 

And you end up with this:

var b = new B(); b.doYourWork(); // Not accessible ((someI)b).doYourWork(); // Accessible 
like image 111
Rob Avatar answered Sep 24 '22 22:09

Rob