Programmatically using a string as object name when instantiating an object

You need to be clear in your mind about the difference between an object and a variable. Objects themselves don't have names. Variable names are decided at compile-time. You can't access variables via an execution-time-determined name except via reflection.

It sounds like you really just want a Dictionary<string, CustomObj>:

Dictionary<string, CustomObj> map = new Dictionary<string, CustomObj>();

foreach (string name in stringArray)
{
    map[name] = new CustomObj(name);
}

You can then access the objects using the indexer to the dictionary.

If you're really trying to set the values of variables based on their name at execution time, you'll have to use reflection (see Type.GetField). Note that this won't work for local variables.


You can't.

You can place them into a dictionary:

Dictionary<String, CustomObj> objs = new Dictionary<String, CustomObj>();

foreach (string i in stringarray)
{
    objs[i] = new CustomObj(i);
}

But that's about as good as it gets.

If you store the objects in fields in your class, like this:

public class SomeClass
{
    private CustomObj fooObj;
    private CustomObj barObj;
    private CustomObj bazObj;
}

Then you can reach them through reflection. Let me know if that's the route you want to take.

Tags:

C#

Oop