Robin Rodricks
Robin Rodricks

Reputation: 114126

How to access a private base class field using Reflection

I'm trying to set the private "visible" field on a variable of type BaseClass.

I've successfully accessed the variable of type ChildClass, and the FieldInfo for the "visible" field on the BaseClass.

But when I try to set/get the value of the field, I get the error System.Runtime.Remoting.RemotingException: Remoting cannot find field 'visible' on type 'BaseClass'.

So Is there a way to "down cast" a variable of type ChildClass to BaseClass in order for the reflection to work?


Edit: The exact code I'm using:

// get the varible
PropertyInfo pi = overwin.GetProperty("Subject", BindingFlags.Instance|BindingFlags.Public);
CalcScene scene = (CalcScene) pi.GetValue(inwin, null);

// <<< scene IS ACTUALLY A TYPE OF DisplayScene, WHICH INHERITS FROM CalcScene

// get the 'visible' field
Type calScene = typeof(CalcScene);
FieldInfo calVisible = calScene.GetField("visible",BindingFlags.Instance|BindingFlags.NonPublic);

// set the value
calVisible.SetValue(scene, true); // <<< CANNOT FIND FIELD AT THIS POINT

The exact class structure:

class CalcScene  
{
    private bool visible;
}

class DisplayScene : CalcScene  
{
}

Upvotes: 2

Views: 2399

Answers (2)

Glory Raj
Glory Raj

Reputation: 17701

you can try like this

    class B
    {
        public int MyProperty { get; set; }
    }

    class C : B
    {
        public string MyProperty2 { get; set; }
    }

    static void Main(string[] args)
    {
        PropertyInfo[] info = new C().GetType().GetProperties();
        foreach (PropertyInfo pi in info)
        {
            Console.WriteLine(pi.Name);
        }
    }

produces

    MyProperty2
    MyProperty

Upvotes: 3

dkackman
dkackman

Reputation: 15579

Here is some code that demonstrates the difference between getting a field vs a property:

  public static MemberInfo GetPropertyOrField(this Type type, string propertyOrField)
  {
      MemberInfo member = type.GetProperty(propertyOrField, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
      if (member == null)
          member = type.GetField(propertyOrField, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);

      Debug.Assert(member != null);
      return member;
  }

Upvotes: 1

Related Questions