Getting a reference to an object from the corresponding FieldInfo object???

  • Thread starter Thread starter dotnetguy
  • Start date Start date
D

dotnetguy

Hello,

having a FieldInfo object I'd like to get a reference to the
corresponding field object. I know the type of the field object (so I
can do a cast if it is required) but I don't know if FieldInfo indeed
provides a reference to the underlying object and how to get it.
Can anyone help out???


Thx.
Bob Rock
 
You can call GetValue on the FieldInfo object.

//example code (I haven't compiled this code so no garuntees)
MyClass m = new MyClass();
FieldInfo fi = m.GetType.GetField("age");
int age = (int)(fi.GetValue(m));

class MyClass
{
public int age = 23;
}

FYI:
You cannot cast the FieldInfo object as it is only metadata of the Field and
not the Field itself. And I don't think the cast operators are overloaded
for you to do this either. Since they don't know what your field type is, I
am not even sure if there is a way for them to provide a cast operator.
 
Hi,

AFAIK there is no way of doing it, a FieldInfo is related to the type
itself, it has no connection with a particular instance of the given type.

do u have any way to keep the instance from where you called GetType() ?


cheers,
 
Back
Top