Get a container class instance from a FieldInfo

1.3k Views Asked by At

I am working with C# reflection here: I have a FieldInfo of a property and I would like to get the instance of the class it belong (so I can reach the content of another property):

for exemple take this class:

class MyClass
{
   public int A { get; set; }
   public int B { get; set; }
}

in some part of the code I have

void Function(FieldInfo fieldInfoOfA)
{
  // here I need to find the value of B
}

Is this possible ?

2

There are 2 best solutions below

0
On BEST ANSWER

Is this possible ?

No. Reflection is about discovery of the metadata of a type. A FieldInfo does not contain any information about a particular instance of that type. This is why you can get a FieldInfo without even creating an instance of the type at all:

typeof(MyClass).GetField(...)

Given the snippet above, you can see that a FieldInfo can be obtained without any dependence on a particular instance.

0
On

FieldInfo provides access to the metadata for a field within a class, it is independent of a specified instance.

If you have an instance of MyClass you can do this:

object Function(MyClass obj, FieldInfo fieldInfoOfA)
{
    var declaringType = fieldInfoOfA.DeclaringType;

    var fieldInfoOfB = declaringType.GetField("B");

    return fieldInfoOfB.GetValue(obj);
}