.net reflection of privates

On IRC, there was someone who had come to the (incorrect) conclusion that unlike Java, good ol .NET reflection could only see public members.  Nevermind that reflection would arguably be useless in such situations (outside of dynamic language-type needs), but the (simple) answer is to use the BindingFlags parameter to specify Instance (default is static) and NonPublic (default is public) when looking for targets with those properties.

23:40 [ Zero] I think I’ve found the problem.  Reflection can only see public members.

Not sure how this will copy-paste, but hopefully you’ll get the point:

using System;
using System.Reflection;

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            Type targetType = typeof(HasPrivateMethodFoo);
            ConstructorInfo ctor = targetType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null);
            MethodInfo method = targetType.GetMethod(“Foo”, BindingFlags.Instance | BindingFlags.NonPublic);
            object instance = ctor.Invoke(new object[0]);
            method.Invoke(instance, new object[] { “string to print” });
        }
    }

    class HasPrivateMethodFoo
    {
        private HasPrivateMethodFoo()
        {
            // do nothing
        }
        private void Foo(string bar)
        {
            Console.WriteLine(bar);
        }
    }
}

Advertisements