Alex Rivera | Logout

Programmatically using a string as object name when instantiating an object

Asked 2008-11-24T12:16:14.810
10

This is a contrived example, but lets say I have declared objects:

CustomObj fooObj;
CustomObj barObj;
CustomObj bazObj;

And I have an string array:

string[] stringarray = new string[] {"foo","bar","baz"};

How can I programmatically access and instantiate those objects using the string array, iterating using something like a foreach:

foreach (string i in stringarray) {
    `i`Obj = new CustomObj(i);
}

Hope the idea I'm trying to get across is clear. Is this possible in C#?

Edit
Report

3 Answers

31

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.

answered 2008-11-24T12:19:10.640
2

you can use a find function:

    public static Control FindControl(string controlId, Control container)
    {
        if (container.ID == controlId)
            return container;

        foreach (Control control in container.Controls)
        {
            Control c = FindControl(controlId, control);
            if (c != null)
                return c;
        }
        return null;
    }

and then you will get your control, based on index like this: TextBox firstname = (TextBox) FindControl(string.Concat("TextBox", index.ToString()), this); I hope this helps.

answered 2009-06-19T18:36:28.267
0

One option is the totally dynamic route, as per this article, where you specify a code block in a string and then compile/run it from within your program

answered 2008-11-24T12:21:13.800

Your Answer