Reputation: 103
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.
Upvotes: 0
Views: 598
Reputation: 4387
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 string
with a single Expression
.
Dictionary<string, Expression> myExpressionDict = new Dictionary<string, Expression>();
foreach(string s in StringArray) {
if(!SomeDifferentArray.Contains(s)) {
myExpressionDict[s] = new Expression();
}
}
After this loop finishes, for any string s
in your original SomeArray
, you can do myExpressionDict[s]
to get its associated Expression
object.
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).
Upvotes: 2
Reputation: 3938
You could use a Map or a Dictionary. Not exactly what you are asking but a lot more simple.
Upvotes: 0