piotrek
piotrek

Reputation: 1363

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

Upvotes: 4

Views: 14414

Answers (3)

John Bledsoe
John Bledsoe

Reputation: 17692

Am I correct to assume that you have two variables and that you want to get one or the other dynamically? I don't believe you can do this with reflection (at least not easily), but you can do it with functions quite easily.

// Declaration
class SomeMechanism
{
    public static T Get<T>(Func<T> getter);
}

// Usage
Car car1;
Car car2;

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

Upvotes: 1

Bala R
Bala R

Reputation: 109027

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

Upvotes: 7

jason
jason

Reputation: 241779

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

Upvotes: 4

Related Questions