Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get object by reflection

I'm looking for mechanism in c# works like that:

Car car1;
Car car2;

Car car = (Car)SomeMechanism.Get("car1");

car1 and car2 are fields

So I want to get some object with reflection, not type :/ How can I do it in c# ?

like image 407
piotrek Avatar asked Dec 22 '22 13:12

piotrek


2 Answers

It's not possible for local variables but If you have a field, you can do

class Foo{

    public Car car1;
    public Car car2;
}

you can do

object fooInstance = ...;

Car car1 = (Car)fooInstance.GetType().GetField("car1").GetValue(fooInstance);
like image 158
Bala R Avatar answered Jan 05 '23 17:01

Bala R


It looks like you're trying to access local variables by reflection. This is not possible. Local variables are not accessible by reflection.

like image 33
jason Avatar answered Jan 05 '23 17:01

jason