Suppose I have a list of objects
List DogList = new List();
and I want to automatically add objects to it, li
You are looking for this?
for(int i =0; i<100;i++){
DogList.Add(new dogClass());
}
Im not sure what are your intentions, but maybe you want to that in a loop:
for(int i = 0; i < 10; i++)
{
dogList.Add(new DogClass());
}
just use a loop
for(int i = 0; i<10; i++)
{
Doglist.add(new dogClass("puppy" + i.ToString()));
}
You do not have to store them in a variable first:
DogList.Add(new DogClass());
is ok.
If you want to add multiple:
DogList.Add(new DogClass());
DogList.Add(new DogClass());
DogList.Add(new DogClass());
Or if you want this flexible:
for(int i = 0; i < NR_OF_OBJECTS_TO_ADD; i++) {
DogList.Add(new DogClass());
}
Why do you want to do that?
Create a method to add a dog:
void AddDog()
{
DogList.Add(new dogClass());
}
And access them by index:
dogClass GetDog(Int32 index)
{
return DogList[index];
}
There is no way in C# to create names (or in other words identifier) of objects dynamically.
All the above solutions given are right in a sense that they created dynamic objects for you but not dynamic object with a "dynamic NAME".
One roundabout way which may fit your requirement is: by using a keyValue pair.
for example:
Dictionary<string, dogClass> DogList = new Dictionary<string, dogClass>(3);
for(int i=1; i<=10; i++)
{
DogList.Add("myDog"+i,new dogClass());
}
Now to access each of these dogClass from the DogList....u can use->
DogList["myDog1"]
or DogList["myDog5"]
......
or if ur dogClass had a property called Name. The Name could be used as the Key.
List<dogClass> DogList = new List<dogClass>(3);
for(int i=1; i<=10; i++)
{
DogList.Add(new dogClass(Name:"myDog"+i));
}
GetDogWithName("myDog1"); //this method just loops through the List and returns the class that has the Name property set to myDog1
Here, for the plain eye or the layman...you have created objects with unique Names. But for you and me...they are strings not the name of the object.
On a funnier thought.... if C# had given us a function(or property) something like this:
int myName = 0;
now if
myName.GetIdentifierName()
returned "myName"..... uhhhh.. Now i dont want to think beyond this .....what should happen when i set the property to :
myName.SetIdentifierName() = "yourName"; //what happens to myName????