Getting variable by name in C #

Is there a way to get the value of a variable simply by knowing its name, for example:

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

When I usually access a variable like this

 double temp = MyClass.VariableName; 
+7
source share
2 answers

You can use reflection . For example, if the 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 this is a public field :

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

Of course, you must understand that thinking is not exempt from costs. There may be a penalty for performance compared to direct access to properties / fields.

+19
source

You will need to use reflection. See http://msdn.microsoft.com/en-us/library/z919e8tw(v=vs.80).aspx for more details.

0
source

All Articles