Reflection on existing variable

  • Thread starter Thread starter Brian Bischof
  • Start date Start date
B

Brian Bischof

I'm trying to loop through each field in a class and print its value out.
Using reflection I can build a list of the fields/methods/properties etc.
and I can use InvokeMember() to create a new class in memory. But I can only
do this by using the an object's Type and creating an empty instance of it.
I need to use an object variable that already exists and call these same
methods on it. Is there a way to perform reflection on an existing variable?

I tried to call InvokeMember() and pass it the existing variable so that it
copies it into memory, but no such override exists.

I've also experimented with Activator.CreateInstance() but it doesn't take
existing objects either.

Thanks.
 
Brian Bischof said:
I'm trying to loop through each field in a class and print its value out.
Using reflection I can build a list of the fields/methods/properties etc.
and I can use InvokeMember() to create a new class in memory. But I can only
do this by using the an object's Type and creating an empty instance of it.

No, you can show a list of fields etc without creating an instance at
all - why do you think you need an instance? You'd need an instance to
list instance field *values* of course.
I need to use an object variable that already exists and call these same
methods on it. Is there a way to perform reflection on an existing variable?

Absolutely - just do it as you would with a newly created object.
I tried to call InvokeMember() and pass it the existing variable so that it
copies it into memory, but no such override exists.

I don't know what you mean by "copies it into memory" here, but
specifying the existing object reference as the "target" parameter will
work fine.
I've also experimented with Activator.CreateInstance() but it doesn't take
existing objects either.

CreateInstance is just going to create a new instance, so I don't see
where an existing instance would come in.
 
Thanks Jon,

All the examples on the internet always pass an empty object. None of them
said that the methods work with an existing object. Thanks! Here is my code
if anyone needs it (since it doesn't seem to be addressed anywhere else on
the internet).

//Use Reflection on an existing object variable.
class Class1
{
[STAThread]
static void Main(string[] args)
{
//Instantiate an object variable
ClassTest obj = new ClassTest();
myObj.x = 5;
//Print out the value '5' using reflection
Type t = myObj.GetType();
int z;
z = (int)t.InvokeMember
("x",System.Reflection.BindingFlags.GetField,null,myObj,null);
Console.WriteLine(z);
Console.ReadLine();
}
}
class ClassTest
{
public int x;
}
 
Back
Top