kopaty4
kopaty4

Reputation: 2296

How to dynamically set variable value with C#?

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.

Upvotes: 1

Views: 2522

Answers (3)

Ahmad Mageed
Ahmad Mageed

Reputation: 96477

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.

Upvotes: 4

Wiktor Zychla
Wiktor Zychla

Reputation: 48230

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" } );
    }
}

Upvotes: -1

C. K. Young
C. K. Young

Reputation: 223003

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

Upvotes: 1

Related Questions