tags:

views:

358

answers:

5

I wish to dynamically create and name instances of my object at runtime as I add them to a list class I somehow thought this would be a simple matter in c# but thus far I have been unable to find any information on how to achieve this.

for the brief description I have a custom class that during runtime I wish to create an array list and populate it with objects of the custon class but name the objects as they're being added to the list using the loop index and a standard name.

Is this possible?

A: 

If you want to give them a name then add them to a mapping instead of a list.

Ignacio Vazquez-Abrams
+2  A: 

Objects don't have names in .NET.

Also, don't use the ArrayList class. Use List<T> instead.

John Saunders
Not trying to be argumentative here, but I'd say the opposite is true because you generally assign your objects to a variable at some point, even if only vaguely by burying them in a list, by which you have a means to locate and identify them in your code... effectively providing a name of sorts for them.Then again, you've always the option where you can provide a name property for your objects...Come to think of it, the same can be said of any language, visual or otherwise. :-)
S.Robins
It doesn't sound like the OP is talking about variables here, but rather objects. Objects do not have names, in general.
John Saunders
I'm awake now and firing on all cylinders, but S Robins is spot on about what I was trying to achieve at the time. Sorry about the lack of clarity but being up for more that 28 hours straight can shotgun one's reasoning faculties
Dark Star1
+1  A: 

Sort of an odd question, as you can't "name" objects.

However you could do what it sounds like you are trying to achieve using a generic dictionary (Dictionary<string, MyCustomType>). The string key in the dictionary is sort of like an object name, and the value the key corresponds to contains the object instance.

Phil Sandler
+1  A: 

Are you maybe looking for something like System.Collections.Generic.Dictionary<>..?

KristoferA - Huagati.com
+1  A: 

You can either have a list that allows you to access its elements by an index or have a dictonary that allows you the same with any particular type:

List<YourClass> yourList = new List<YourClass>();
YourClass instance = new YourClass();
yourList.Add(instance);
YourClass instance2 = yourList[0];

For example, if you want your dictionary with a string key ("name"):

Dictonary<string, YourClass> dict = new Dictonary<string, YourClass>();
YourClass instance = new YourClass();
dict.Add("someName", instance);
YourClass instance2 = dict["someName"];

Unlike in PHP, there's no inbuilt collection type in C# that allows you to access its members by both an index or a key. You can always create your own though.

DrJokepu
my apologies for not being clear. It's 0430 and I'm long over due for bed :) Saunders you're quite right.
Dark Star1