10

Is it possible to use a dynamic variable (not sure about naming) in C#?

In PHP, I can do

$var_1 = "2";
$var_2 = "this is variable 2";

$test = ${"var_".$var_1};

echo $test;

output: this is variable 2;

Can we do this in C#?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Moon
  • 22,195
  • 68
  • 188
  • 269
  • 1
    let's not compare a scripting language with a programming language. You can do the same in plain old ASP as it is also a scripting language, but C# is a programming language that uses OOP. Just to add, you have Dynamic Variables in .NET 4 – balexandre Dec 21 '10 at 00:49

5 Answers5

10

In C#, you use dictionaries to associate values with strings.

Martin v. Löwis
  • 124,830
  • 17
  • 198
  • 235
9

No, basically. The compiler doesn't guarantee that method variables will exist (in their form as written), or with names...

If they were fields (instance or static), then you could use reflection to get the values; but not method variables. For what you want, perhaps use a dictionary as a substitute?

var vars = new Dictionary<string,object>();
vars["var_1"] = "2";
vars["var_2"] = "this is variable 2";

Console.WriteLine(vars["var_" + vars["var_1"]]);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • I don't understand this part of the second sentence "method variables will exist (in their form as written) or with names...". I understand the rest of your answer, I just don't understand the meaning of that sentence. Could you clarify what that means? – Lasse V. Karlsen Apr 16 '10 at 19:47
  • He means that the variable names are not guaranteed to be saved until runtime, so even if you could do something like that, "$var_2" wouldn't exist after compiling. – BlueRaja - Danny Pflughoeft Apr 16 '10 at 21:21
1

Not sure if this works with local variables (and most likely it doesn't since they're stored as indexes), but you could access class properties through reflection.

Blindy
  • 65,249
  • 10
  • 91
  • 131
1

If your var is a class field, then you can use the static GetField method from class Type to obtain field information, such as its current value.

João Silva
  • 89,303
  • 29
  • 152
  • 158
1

You are not looking for simple arrays?

string[] myArray = new string[2];

myArray[0] = "2";
myArray[1] = "this is variable 2"

Otherwhise dictionary is the way to go.