views:

328

answers:

2

How does one obtain programmatically a reference to the object of which a FieldInfo object is a field?

For example, I'd like something like this:

myFieldInfo.GetOwner(); // returns the object of which myFieldObject is a field
+4  A: 

Try this:

myFieldInfo.DeclaringType
Andrew Hare
Thank you very much ... it worked!
JaysonFix
Whoops, I spoke too soon. I wanted the *object* of which myFieldInfo is a field, not the class of that object.
JaysonFix
@JaysonFix: Sorry, there is no way to return a reference to the object itself - the only thing you can do is retrieve a reference to the *type* that the field belongs to. Please see Jared's answer for more info about that.
Andrew Hare
+8  A: 

Unfortunately you can't because the relationship works the opposite way. A FieldInfo object represents metadata that is independent of any instance. There is 1 FieldInfo for every instance of an object's field.

This is true in general about all Metadata objects such as Type, FieldInfo, MethodInfo, etc ... It is possible to use the metadata objects to manipulate an instance of an object. For instance FieldInfo can be used to grab an instance value via the GetValue method.

FieldInfo fi = GetFieldInfo();
object o = GetTheObject();
object value = fi.GetValue(o);

But a metadata object won't ever be associated with an instance of the type.

JaredPar
Thank you, Jared.
JaysonFix