How do I name variables dynamically in C#?

Brandon picture Brandon · Feb 17, 2011 · Viewed 42.4k times · Source

Is there a way to dynamically name variables?

What I need to do is take a list of variable names from an input file and create variables with those names. Is this possible?

Something like:

Variable <dynamic name of variable here> = new Variable(input);

Assume that I already have the Variable class taken care of, and the name of the variable is contain in a string called strLine.

Answer

Ben Voigt picture Ben Voigt · Feb 17, 2011

Use a Dictionary<string, Variable>.

e.g.

var vartable = new Dictionary<string, Variable>();
vartable[strLine] = new Variable(input);