2

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 ?

Titan
  • 181
  • 2
  • 9
  • Do you have an object of MyClass in scope at the same time you have fieldInfoOfA in scope? – MatthewMartin Feb 16 '16 at 20:11
  • I have nothing but this FieldInfo coming from external code. To add some context I'm working with unity's PropertyDrawer (http://docs.unity3d.com/ScriptReference/PropertyDrawer-fieldInfo.html), but it's not relevant. – Titan Feb 16 '16 at 20:14
  • If you need the value of a field via reflection, check out this question: https://stackoverflow.com/questions/6961781/reflecting-a-private-field-from-a-base-class?rq=1 – MatthewMartin Feb 16 '16 at 20:16
  • FWIW, `A` and `B` on your class are properties, not fields. A FieldInfo would not work for A or for B. – vcsjones Feb 16 '16 at 20:16

2 Answers2

3

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.

vcsjones
  • 138,677
  • 31
  • 291
  • 286
2

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);
}
Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53