Why is this private method executed from another class?

I created and implemented the interface explicitly, as shown below.

public interface IA { void Print(); } public class C : IA { void IA.Print() { Console.WriteLine("Print method invoked"); } } 

and then executed by the following main method

 public class Program { public static void Main() { IA c = new C(); C c1 = new C(); foreach (var methodInfo in c.GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)) { if (methodInfo.Name == "ConsoleApplication1.IA.Print") { if (methodInfo.IsPrivate) { Console.WriteLine("Print method is private"); } } } c.Print(); } } 

and the result that I got on the console:

Printing method is private

The printing method is called.

So my question is why this private method was executed from another class?

As far as I understand, the accessibility of a private member is limited by his type of announcement, why he behaves so strangely.

+5
source share
1 answer

So my question is why this private method was executed from another class?

Well, this is just a variety - private. It uses an explicit implementation of the interface - it is accessible through the interface, but only through the interface. So even in class C, if you had:

 C c = new C(); c.Print(); 

which could not compile but

 IA c = new C(); c.Print(); 

... which will work everywhere, because the interface is public.

The C # specification (13.4.1) notes that an explicit interface implementation is unusual in terms of access:

Explicit implementations of interface elements have different accessibility characteristics than other members. Because explicit implementations of interface elements are never accessible through their full name in a method call or access to a resource, they are, in a sense, private. However, since they can be accessed through an instance of the interface, in a sense they are also publicly available.

+6
source

All Articles