I need to declare a variable with a name that matches a string.
This is what I need to work, but in reality it compiles with a new expression instance with the name "s" (I need it to take the name that is stored in the string s)
How can I solve this?
Code:
foreach (string s in StringArray)
{
if (SomeDifferentArray.Contains(s) != true)
{
Expression s = new Expression();
}
}
I need a new instance of expression for each string in StringArray, and each of those expressions needs to be named according to the literal that the string holds.
This seems like a use case for a mapping collection. I’m not a C# user myself but I suspect the dictionary class would be the one to go to:
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
C# is a compiled language, so you can’t create compile-time variables that are dependent on run-time data. However, you can use a map-style data structure to associate a unique key object with a single value object. In your case, you can use it to associate each
stringwith a singleExpression.After this loop finishes, for any string
sin your originalSomeArray, you can domyExpressionDict[s]to get its associatedExpressionobject.In C# this structure is called a “dictionary.” This same data struture may also go by the names “map” or “hash,” depending on your programming language or library. For example, in the Java collections framework it’s referred to as Map, in Ruby they use the term hash, and in Python it goes by the name dictionary (or dict for short).