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 programatically 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#?
Thanks in advance.
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.
you can use a find function:
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.
use this.Controls.Find(control_name,true)[0]...just remember to cast it
You can't.
You can place them into a dictionary:
But that's about as good as it gets.
If you store the objects in fields in your class, like this:
Then you can reach them through reflection. Let me know if that's the route you want to take.
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>
: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.
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?