Search code examples
c#reflectionfieldinfo

Get a container class instance from a FieldInfo


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 ?


Solution

  • 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.