Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting variable by name in C#

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;
like image 274
Andreas Avatar asked Feb 19 '11 21:02

Andreas


People also ask

Can you print a variable name in C?

How to print and store a variable name in string variable? In C, there's a # directive, also called 'Stringizing Operator', which does this magic. Basically # directive converts its argument in a string. We can also store variable name in a string using sprintf() in C.

Can variable name in C?

Variable names in C are made up of letters (upper and lower case) and digits. The underscore character ("_") is also permitted. Names must not begin with a digit. Unlike some languages (such as Perl and some BASIC dialects), C does not use any special prefix characters on variable names.

What is naming variables in C?

Names can contain letters, digits and underscores. Names must begin with a letter or an underscore (_) Names are case sensitive ( myVar and myvar are different variables) Names cannot contain whitespaces or special characters like !, #, %, etc. Reserved words (such as int ) cannot be used as names.

How do you find the variable name?

The variable name must describe the information represented by the variable. A variable name should tell you concisely in words what the variable stands for. Your code will be read more times than it is written. Prioritize how easy your code is to read over than how quick it is to write.


1 Answers

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.

like image 102
Darin Dimitrov Avatar answered Nov 08 '22 02:11

Darin Dimitrov