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#?

1
  • Maybe, are you looking to assign objects to instance variables at runtime or just create objects dynamically? Commented Nov 24, 2008 at 12:19

8 Answers 8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I think this response should earn the "Intuiting What The Customer REALLY Wanted" award. Good answer
And what if the 'CustomObj' does not have a constructor?
@Jnr: Then the question doesn't apply, given that the OP is in a situation where there is a constructor. Basically, "how you construct instances" and "how you keep track of instances in a collection" are entirely orthogonal concerns.
4

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.

Comments

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.

1 Comment

ID is not a property of Control. You can use Name property: "if (container.Name == controlId)"
2

use this.Controls.Find(control_name,true)[0]...just remember to cast it

Comments

0

This is possible using reflection if the variables are class member variables, but it's hideously slow for anything more than very specialized applications. I think if you detail what you're trying to do, we can better offer suggestions. There's very rarely a case where you should access a variable like you're doing.

Comments

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

Comments

0

Another option, less flexible, but simpler is via Activator.CreateInstance - where you ask for a new object to be created - it won't assign to dynamic variables, but is that needed?

Comments

0

@jotte: Thanks alot for that function. I used it and it works! Except that you need to change container.ID by container.Name

Then you just need to use something like (this example is for checkbox, but any type of variable could work):

string Test = "cbACn" + i.ToString(); CheckBox cbTest = (CheckBox)FindControl(Test, gbACSCAT); if (cbTest != null) { cbTest.Checked = true; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.