Home > Software engineering >  Can you make a variable with a variable name?
Can you make a variable with a variable name?

Time:04-06

So what I want to try and do is a thing you can do in javascript. I want to be able to add a child to some sort of object but I want the name of that child to be variable. In javascript you can do something like

const obj = new Object();

let childName = "child1";

obj[childName] = new Object();

Is something like this possible in C#?

CodePudding user response:

You can use a dictionary:

Dictionary<string,object> obj = new Dictionary<string,object>();
string childName = "child1";
obj[childName] = new Object();

If you know the type of the objects you want to add to your dictionary, you can also specify it. For example, if you want to use only integers, you could write Dictionary<string,int> and then you don't need casting.

  • Related