Dark Star1
Dark Star1

Reputation: 7403

how do I dynamically create and name objects at runtime in C#?

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?

Upvotes: 4

Views: 4281

Answers (5)

Tamas Czinege
Tamas Czinege

Reputation: 121314

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.

Upvotes: 2

KristoferA
KristoferA

Reputation: 12397

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

Upvotes: 0

Phil Sandler
Phil Sandler

Reputation: 28016

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.

Upvotes: 0

John Saunders
John Saunders

Reputation: 161773

Objects don't have names in .NET.

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

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798666

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

Upvotes: 0

Related Questions