14

Is there a way to get the value of a variable just by knowing the name of it, like this:

double temp = (double)MyClass.GetValue("VariableName");

When I normally would access the variable like this

double temp = MyClass.VariableName;
1
  • 1
    I'm curious as to what context you would need to do this, where accessing a value as a property normally would not suffice. Commented Feb 19, 2011 at 21:10

1 Answer 1

32

You could use reflection. For example if PropertyName is a public property on MyClass and you have an instance of this class you could:

MyClass myClassInstance = ...
double temp = (double)typeof(MyClass).GetProperty("PropertyName").GetValue(myClassInstance, null);

If it's a public field:

MyClass myClassInstance = ...
double temp = (double)typeof(MyClass).GetField("FieldName").GetValue(myClassInstance);

Of course you should be aware that reflection doesn't come free of cost. There could be a performance penalty compared to direct property/field access.

Sign up to request clarification or add additional context in comments.

6 Comments

Be careful; it might be very slow using this frequently.
Would reflection be slower then a 10 case switch filter?
@Andeas, no freaking idea, I bet 5 bucks reflection would be slower but the best would be to measure it in order to be sure and you'd better be sure before putting some code in production.
@Andreas: I bet. A 10 case switch filter is about as slow as a 3 case switch filter.
@Andreas: Just chiming in with what others are saying here. I had a project where I replaced a reflection-based solution with a switch/case and got more than an order of magnitude speedup in several tight loops. For more complex scenarios, it's also worth trying a delegate wrapping a lambda that just fetches the property -- those also can beat reflection by an order of magnitude or more.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.