Reflection with Private Members

By using reflection we can call any function including the private and protected ones. This includes private static methods, constructor methods, normal methods. What we need to do is to get the method by the BindingFlags.Nonpublic flag and then we just use it like a reflected type.

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
 
namespace ReflectPrivateMembers
{
    class Program
    {
        static void Main(string[] args)
        {
            ConstructorInfo ci = typeof(Hello).GetConstructor(BindingFlags.NonPublic| BindingFlags.Instance ,null,System.Type.EmptyTypes,null);
            object helloObject = ci.Invoke(System.Type.EmptyTypes);
            MethodInfo[] helloObjectMethods = helloObject.GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly| BindingFlags.Instance );
 
            foreach (MethodInfo mi in helloObjectMethods)
            {
                mi.Invoke(helloObject, System.Type.EmptyTypes);
            }
            Console.ReadLine();
        }
    }
    public class Hello
    {
        private Hello()
        {
            Console.WriteLine("Private Constructor");
        }
        public void HelloPub()
        {
            Console.WriteLine("Public Hello");
        }
        private void HelloPriv()
        {
            Console.WriteLine("Private Hello");
        }
    }
}

3 Comments

  1. haison8x says:

    Dear, the following exception was thrown

    System.MethodAccessException was unhandled by user code
    Message=”System.Windows.Input.Hello..ctor()”
    StackTrace:
    at System.Reflection.MethodBase.PerformSecurityCheck(Object obj, RuntimeMethodHandle method, IntPtr parent, UInt32 invocationFlags)
    at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
    at System.Reflection.ConstructorInfo.Invoke(Object[] parameters)
    at System.Windows.Input.MyMouseEventArgs.createMouseEventArgs()
    at First.Page.Result_MouseMove(Object sender, MouseEventArgs e)
    at System.Windows.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
    at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)
    InnerException:

  2. Can says:

    that is interesting. The article was written with 2.0 version, but I just checked with 3.5 and it is working.
    What version of .NET are you using ? I wonder if it has something to do with the policies.

  3. [...] easy in Ruby to call the private methods of another object if you really want to. There’s no intimidating ugly barbed-wire fence around them like there is in a language like C#, but there’s a fence nonetheless. And that [...]

Leave a Reply