0

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?

2

2 Answers 2

2

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"];
Sign up to request clarification or add additional context in comments.

4 Comments

what if the datatypes are different?
you can use a HashTable then. That stores objects.
@JasonDam: Can't he use Dictionary<object, object>?
yes he can, depending on the number of elements, using dictionary vs hash will be more or less the same, performance not considering. For the purist, Dictionary<object,object> will do an extra boxing/unboxing on the string. Oh well.
1

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).

2 Comments

@slugster am getting the error: Keyword 'this' is not valid in a static property, static method or static field initializer
@Rohit then use typeof(MyClass) instead of this.GetType() as you cannot use this in a static class.

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.