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.

Community
  • 1
  • 1
kopaty4
  • 2,236
  • 4
  • 26
  • 39

3 Answers3

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.

Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174
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).

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
-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" } );
    }
}
Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106