Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this private method does get executed from another class?

Tags:

c#

private

I Created and implemented an interface explicitly as below.

public interface IA
{
    void Print();
}

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

and Then executed 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 I got on console is:

Print method is private

Print method invoked

So my question is why this private method got executed from other class?

As far as I understand the accessibility of private member is restricted to its declaring type then why does it behave so strangely.

like image 688
Jenish Rabadiya Avatar asked Jun 03 '15 12:06

Jenish Rabadiya


1 Answers

So my question is why this private method got executed from other class?

Well, it's only sort-of private. It's using explicit interface implementation - it's accessible via the interface, but only via the interface. So even within class C, if you had:

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

that would fail to compile, but

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

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

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

Explicit interface member implementations have different accessibility characteristics than other members. Because explicit interface member implementations are never accessible through their fully qualified name in a method invocation or a property access, they are in a sense private. However, since they can be accessed through an interface instance, they are in a sense also public.

like image 189
Jon Skeet Avatar answered Sep 18 '22 05:09

Jon Skeet