Sorry if this is a duplicate, but I didn't find what I need (over 30 minutes of searching the web)
I want to create variable with name from other variable (string) Is there a possibility to do this in c#? I'm new to c#.
Sorry if this is a duplicate, but I didn't find what I need (over 30 minutes of searching the web)
I want to create variable with name from other variable (string) Is there a possibility to do this in c#? I'm new to c#.
No, you can't, and it makes no sense honestly to have a feature like that.
If you want , you can use a dictionary, where you can have the key be a string:
Dictionary<string, RectangleShape> shapes = new Dictionary<string, RectangleShape>();
shapes.Add("nameTheKey", new RectangleShape( ... ));
Then you can simply read the "variable" like
shapes["nameTheKey"]
No, and it doesn't make any sense.
Variable (or more precisely, local) names are only important at compile-time, and they only have values at runtime. If you add a new variable, you'd also need to add code to handle that variable - but how do you write and use that code without the compiler?
However, if you simply want to store some data in a key-value fashion, you can use a dictionary:
var data = new Dictionary<string, decimal>();
The first type argument is the key, and the second is the value. Do note that the values all have to be of the same type, or a type that derives from some common type.
If you want something more like JavaScript, you can have a look at the dynamic features of C# (dynamic
, ExpandoObject
, ...) - but frankly, you'll be better off adopting the idioms of C# 99% of the time.
ExpandoObject
allows you to use code like this:
dynamic item = new ExpandoObject();
((IDictionary<string, object>)item)["Message"] = "Hi!";
Console.WriteLine(item.Message);
But again, it's rarely the best way to do something :)