# Variable variables in C#

## Recommended Posts

_Danneman_    122
In for instance ActionScript (programs flash) there is a possibility of calling a variable by typing a part of its name, and add the rest of the name as the content of another variable. Ex:
var_1 = "Hello";
var_2 = 1;
var_3 = _root["var_" + var_2];

// var_3 gets the value from var_1, ie. "Hello"

Does anything like that exist in C#?

##### Share on other sites
SiCrane    11839
You can do it through the reflection API, check out the System.Reflection namespace. I don't know if there's an easier way.

##### Share on other sites
deej21    152
Hm, there might be an easier way, as I don't know C# well, but you can use arrays in the situation you have there. Something like:

(c++)
//create arrayarray[0] = "hello";int index = 0;myVar = array[index];

This will accomplish the same thing as you posted, but will not be fun or organized to have several variables each in an array like that.

##### Share on other sites
_Danneman_    122
Youre right, its probably easier to use arrays instead. But Ill check out System.Reflection too.

Thanks both for the help :)

##### Share on other sites
smr    2468
            Type t = theObject.GetType();            // field is a member variable            t.GetField("FieldName").GetValue(theObject));            // or get property, which is a property defined like            // int SomeProperty { get{ return 0; } }            t.GetProperty("PropertyName").GetValue(theObject, null));

##### Share on other sites
Zahlman    1682
Does ActionScript have arrays, even? o_O

If you really need to be able to map from a "name" to some "value", then use - a map.

#include <map>#include <string>//...std::map<std::string, std::string> vars;vars["1"] = "Hello";vars["2"] = "1"; // can't store an int. C++ is statically typed.vars["3"] = vars[vars["2"]];

##### Share on other sites
SiCrane    11839
Quote:
 Original post by Zahlman*** source code removed ***

Psst. C#. Not C++.

##### Share on other sites
Conner McCloud    1135
Quote:
Original post by SiCrane
Quote:
 Original post by Zahlman*** source code removed ***

Psst. C#. Not C++.

I'm pretty sure the corresponding class is System.Collections.Generic.Dictionary<Key, Value>

CM

##### Share on other sites
Zahlman    1682
Oops. (Don't know enough C# to help, and yeah, obviously I've been helping way too many people with C++ in a row... come on people, use a more friendly language :) )

##### Share on other sites
DarkZlayer    124
A possible way for this to work is definately an array, here is some sample code if you're still having trouble.

string[] var;
var = new string[];

var[1] = "Hello";
var[2] = "1";
var[3] = var[1] + var[2];

Yes using that code var[2] won't be and integer so if you were to add numbers in that array 1 + 2 = 12 so be careful about that. If you need more help just PM me or something.

##### Share on other sites
Wan    1366
If you're planning to use different variables types (like your AS snippet suggests), I'd recommend using one of (specialized) collections types.
If you only need a fixed list of strings or integers, an array would be a lighter solution.

##### Share on other sites
Khaos Dragon    196
You could define a new native types layer utilizing the map feature so that it works identical to actionscript.

For example you could declare a intX or floatX type and invoke GetVarX( "var_name") or however you define it. You'd of course need to make sure to overload all the arithmetic operators so that they don't lose any flexibility over the real native types.

##### Share on other sites
smr    2468
I think he's trying to get at variables that are just in a specific scope, not elements of some sort of dictionary or map. If that's the case, then he needs to use reflection. I posted code on how to do what he wants to do which will work to get at fields and properties of an object. I don't know how to just get at a variable that isn't part of an object:

using System.Reflection;using System;class dummy{    public int field;    public int Property    {        get { return 10; };    }}void f(){    int someInt = 10;    dummy c = new dummy();    Type dummyType = c.GetType();    int fieldValue = dummyType.GetField("fi" + "eld").GetValue(c);    int propertyValue = propertyType.GetProperty("Prop" + "erty").GetValue(c);    // now how do I get the value of "someInt" by name? It's not a    // property or field, so I can't do a "GetType" on anything.    Console.WriteLine("Value of field: {0}", fieldValue);    Console.WriteLine("Value of Property: {0}", propertyValue);}

##### Share on other sites
Washu    7829
Quote:
 Original post by smrI think he's trying to get at variables that are just in a specific scope, not elements of some sort of dictionary or map. If that's the case, then he needs to use reflection. I posted code on how to do what he wants to do which will work to get at fields and properties of an object. I don't know how to just get at a variable that isn't part of an object:

The simple answer is: You don't. You could, of course, build a preprocessor that would build an internal registry of variables that were added and removed from said registry as they came into scope and left scope, however such a process would be rather...stupid.

He could also build a varadic type with a centralized registry that on construction registered the variable and then he could fetch it from that registry (which is essencially what you would do with a dictionary), which is all _root really is (albeight with a bit more stuff in it).

##### Share on other sites
smr    2468
Quote:
 Original post by WashuHe could also build a varadic type with a centralized registry that on construction registered the variable and then he could fetch it from that registry (which is essencially what you would do with a dictionary), which is all _root really is (albeight with a bit more stuff in it).

But wouldn't GetField and GetProperty accomplish the same thing? Since you have an actual object with a type, you can get at its fields with the GetX methods. Is there a concept in .NET like pythons "__locals__"?

##### Share on other sites
kSquared    1356
Quote:
 Original post by _Danneman_Does anything like that exist in C#?

Not exactly. But there are four ways to approximate this:

1.) Use the System.Reflection methods. For instance, to get the value of a field in a class, use the following.
using System;using System.Reflection;using System.Security;public class Dummy{  public string s = "stored string value";  public string X  {    get    {      return this.s;    }    set    {      this.s = value;    }  }}// Elsewhere in codepublic static void Main(){  // Use a try-catch block in real software to catch  // SecurityExceptions that might arise.  Dummy d1 = new Dummy();  Dummy d2 = new Dummy();  d2.X = "foo";  Type t = Type.GetType("Dummy");  FieldInfo fi = t.GetField("s"); // <-- equivalent variadic specification  // prints "stored string value"  Console.WriteLine("The value of the d1 field is: {0}", fi.GetValue(d1));  // prints "foo"  Console.WriteLine("The value of the d2 field is: {0}", fi.GetValue(d2));}

2.) Use a GenericDictionary to store name-value pairs.

3.) Use an array, if the values are all the same type.

4.) Wait for C# 3.0. Then you can use (3) even if the values aren't all the same type, and the compiler will infer their type from the way in which the value is used.

##### Share on other sites
Washu    7829
Quote:
 Original post by smrBut wouldn't GetField and GetProperty accomplish the same thing? Since you have an actual object with a type, you can get at its fields with the GetX methods. Is there a concept in .NET like pythons "__locals__"?

No, because the instances wouldn't need to be class members. That particular solution is ugly though.
string name = "v";int index = 1;...Var v1(name + index);v = something;...Var var = Var.Get(name + index);

Disguised globals...silly idea.