Getting Variable by Name in C#

get name of a variable or parameter

Pre C# 6.0 solution

You can use this to get a name of any provided member:

public static class MemberInfoGetting
{
public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
{
MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
return expressionBody.Member.Name;
}
}

To get name of a variable:

string testVariable = "value";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);

To get name of a parameter:

public class TestClass
{
public void TestMethod(string param1, string param2)
{
string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1);
}
}

C# 6.0 and higher solution

You can use the nameof operator for parameters, variables and properties alike:

string testVariable = "value";
string nameOfTestVariable = nameof(testVariable);

Getting variable by name in C#

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.

Get variable name in C#

You can use

var name = nameof(x);

to get "x" in a string named "name", where x is the variable you want.

However, it will only work with modern flavours of C#.
For older ones, you'll have to use Expression, which is a PITA, both for performances and in terms of code complexity for a such simple need.

edit : more details here : get name of a variable or parameter

Get variable name from object array

This is impossible. The names test1 and test2 are not stored in the variable array but pointers to the location of the data. Using .net6 on .NETFiddle and the nameof method, the compiler tells you that the expression does not have a name.

.NETFiddle

Get Variables in struct by name

The minimum change to make is to pass the instance (mystruct) to the GetValue method:

private sting GetStingfromStruct(string variableName)
{
return (string)mystruct.GetType().GetField(variableName).GetValue(mystruct);
}

You should also add checks to make sure the string value is actually a field name, etc.

But I would echo other comments and answers that this is not a great design unless you're forced to use a struct for some reason.



Related Topics



Leave a reply



Submit