0

I have recently read the whole concepts of Reflection and I know the main idea of using this instrument of C# But i still can not understand one of it's aspects. I think,Encapsulation does not have any meaning,if anyone has this ability to execute a private method through reflection.Would you mind letting me know about this misunderstanding ?

Calling a private method using reflection

        string methodName = "";

        Type aclass = typeof (AClass);
        object obj = Activator.CreateInstance(aclass);

        Type t = typeof (AClass);
        MethodInfo [] mi = t.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
        methodName = mi[0].Name;
        MethodInfo PrivateMethod = typeof (AClass).GetMethod(methodName,BindingFlags.NonPublic | BindingFlags.Instance);

        Console.WriteLine(PrivateMethod.Invoke(obj,null));
        Console.ReadLine();

Class AClass has a private method

internal class AClass
    {
        private bool First()
        {
            return true;
        }
     }

Output :

True

Mahmood Shahrokni
  • 226
  • 1
  • 3
  • 12
  • 2
    you might want to take a look at [this answer](http://stackoverflow.com/questions/3300680/does-reflection-breaks-the-idea-of-private-methods-because-private-methods-can) – therak Nov 09 '15 at 09:28

1 Answers1

0

Accessing private method should be in the context of Unit Testing especially when dealing with legacy code.

user310291
  • 36,946
  • 82
  • 271
  • 487