Suppose I have a list of objects
List DogList = new List();
and I want to automatically add objects to it, li
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 DogList = new Dictionary(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 DogList = new List(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????