Get object by reflection

piotrek picture piotrek · Jun 6, 2011 · Viewed 11.6k times · Source

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# ?

Answer

Bala R picture Bala R · Jun 6, 2011

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);