Bronsoner Bronsoner - 3 months ago 12
C# Question

C# How to create an object with generated name?

Normally I'd use

MyObject Obj1 = new MyObject(constructors);


but what I need is for the code to create an object for me and assign a name for it by itself based on variable.

string objectname = HakunaMatata


MyObject [I want HakunaMatata here] = new MyObject;


objectname = SomethingNew


MyObject [I want SomethingNew here] = new MyObject;


so how do I do it?

Answer

You're looking for a Dictionary<TKey,TValue>. This enables you to use a string as the "key" and have instances as the value.

string objectname = "HakunaMatata"
var myDictionary = new Dictionary<string,MyObject>();
myDictionary.Add(objectname, new MyObject()); // what a wonderful day!

you can later lookup & use your object by using the same key

MyObject makunaMatataInstance = myDictionary["HakunaMatata"]; // or use the variable "objectname" again