Using C#, is it possible to access the content of a variable whose name is stored in another string variable?
eg.
string str ="ABCDEFG";
string variable = "str";
How could I access the value of str using variable?
Using C#, is it possible to access the content of a variable whose name is stored in another string variable?
eg.
string str ="ABCDEFG";
string variable = "str";
How could I access the value of str using variable?
you probably can, but that's too complicated. Have you thought of using the Dictionary class?
Dictionary<string,string> myDictionary = new Dictionary<string,string>();
myDictionary["str"] = "ABCDEF";
var valueinstr = myDictionary["str"];
Dictionary<object, object>?Yes you can by using reflection.
var fieldInfo = this.GetType().GetField(variable);
string theValue = (string)fieldInfo.GetValue(this);
With the reflection approach you get an object that describes the property, then you use it to retrieve the value from a specific instance of a class. If your property is not public then you will have to specify the correct BindingFlags when you get the PropertyInfo. If you are using a variable like in your example then you need to retrieve a FieldInfo object (another example).
typeof(MyClass) instead of this.GetType() as you cannot use this in a static class.