1

For example, PHP code:

$test = "hello";
${$test} = $test;
echo $hello; // return hello

How to do this in C#? Thanks in advance.


UPD: Dynamic variable in C#? - here is an answer.

4
  • 2
    your example doesn't make much sense to me, care to clarify? Commented Oct 1, 2011 at 15:36
  • 2
    How to dynamically set variable name perhaps? Answered here: stackoverflow.com/questions/1282888/dynamic-variable-in-c Commented Oct 1, 2011 at 15:37
  • @BrokenGlass: In PHP, if $test = 'foo', then ${$test} accesses $foo. Commented Oct 1, 2011 at 15:38
  • is the important part to create a new variable named like a string ? Commented Oct 1, 2011 at 15:38

3 Answers 3

4

This isn't supported in C#. You could use an ExpandoObject and set a member on it, but it's not quite the same as the PHP code. You'll still need to refer to the ExpandoObject by a variable name.

dynamic myObject = new ExpandoObject();
string test = "Hello";
((IDictionary<string, object>)myObject).Add(test, test);
Console.WriteLine(myObject.Hello);

Nonetheless, this doesn't help with code clarity. If all you want to do is map a name to a value you can use a Dictionary, which is really what ExpandoObject uses internally, as demonstrated by the cast in the code above.

Sign up to request clarification or add additional context in comments.

Comments

1

C# is not designed for that sort of thing at the language level. You will have to use reflection to achieve that, and only for fields, not local variables (which cannot be accessed via reflection).

Comments

-1

Such dynamic access to class members can be achieved via reflection.

class Foo
{
    string test;
    string hello;

    void Bar()
    {
        test = "hello";

        typeof(Foo).InvokeMember( test, 
           BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetField, 
           null, this, new object[] { "newvalue" } );
    }
}

Comments

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.