Raghav55
Raghav55

Reputation: 3135

Reflection of protected member of a class

using System;
using System.Reflection;

namespace Reflection

{
    class Test
    {
        protected void methodname()
        {
            Console.WriteLine(("in the world of the reflection"));
            Console.Read();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
           // BindingFlags eFlags = BindingFlags.Default | BindingFlags.Instance | BindingFlags.Public|BindingFlags.NonPublic;
            BindingFlags eFlags = BindingFlags.Instance|BindingFlags.NonPublic;
            Test aTest = new Test();
            MethodInfo mInfoMethod = typeof(Reflection.Test).GetMethod("methodname", eFlags);
            mInfoMethod.Invoke(aTest, null);

        }
    }
}

As per the msdn BindingFlags.Nonpublic is used to access the non private members. If I use only this enum the Getmethod returns null value. But if use the enum - Instance and nonpublic the required method is called. What is the difference between these two. When I have to use instance and public/nonpublic combination.

Upvotes: 6

Views: 5077

Answers (2)

svick
svick

Reputation: 244767

Per the documentation of GetMethod():

You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.

Instance/Static and Public/NonPublic specify two different things and you have to specify both in order to get the result.

Upvotes: 5

C.Evenhuis
C.Evenhuis

Reputation: 26446

If you don't specify the enum, the default is used. If you do, you have to specify both:

  • Public or NonPublic (or both)
  • Static or Instance (or both)

(See the note in the remarks section on http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx)

Upvotes: 1

Related Questions