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
abatishchev
  • 98,240
  • 88
  • 296
  • 433
JaysonFix
  • 2,515
  • 9
  • 28
  • 28
  • 1
    Minor annoyance: C# is a programming language. It doesn't have a FieldInfo. .NET does. Your subject said "C# FieldInfo". – John Saunders Jul 13 '09 at 15:54
  • The text of this question could do with clarification, it reads as though you are looking to aquire an instance object but what you really want is a Type. – AnthonyWJones Jul 13 '09 at 15:56
  • @John: I suggest you review the thousands of other C# questions here that fundementally do the same. Consider whether you would want to comment all those as well. It might be easier to just become reconciled with this bluring since its never going to go away. – AnthonyWJones Jul 13 '09 at 16:00
  • @Anthony: Or, I might raise the issue from time to time instead of just giving up. Among other things I might find that it's a grammar issue instead of a comprehension issue, in which case, I would leave it alone (as I leave most bad grammar alone). I won't find out without asking. – John Saunders Jul 13 '09 at 16:02
  • I wanted to call a method on the object I obtained with FieldInfo and this worked http://stackoverflow.com/a/9235316/74585 – Matthew Lock Mar 17 '15 at 03:03

2 Answers2

12

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
  • 733,204
  • 149
  • 1,241
  • 1,454
3

Try this:

myFieldInfo.DeclaringType
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
  • Whoops, I spoke too soon. I wanted the *object* of which myFieldInfo is a field, not the class of that object. – JaysonFix Jul 13 '09 at 15:55
  • @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 Jul 13 '09 at 15:57