Reputation: 3634
I have quite a few lines of code that create objects and using various parameters with similar object names and constructors. The only thing that is changing is the actual name of the object variable being created, and the name of the objects themselves being passed in. Here is an example of code that matches my current setup:
BackyardObject backyardObject0 = new BackyardObject(cat0, dog0, goat0, piglet0);
BackyardObject backyardObject1 = new BackyardObject(cat1, dog1, goat1, piglet1);
BackyardObject backyardObject2 = new BackyardObject(cat2, dog2, goat2, piglet2);
BackyardObject backyardObject3 = new BackyardObject(cat3, dog3, goat3, piglet3);
BackyardObject backyardObject4 = new BackyardObject(cat4, dog4, goat4, piglet4);
// many many more BackyardObjects being instantiated
As we can see, the names of the object being created match exactly the names of the objects being passed into the constructor. Is it possible to create a loop that would set all this up?
Edit
I think I might have lacked details that were needed to get a correct answer for this question. It isn't a question on "how-to" use a loop, or how to add items to a collection it's more of a question to determine if is it possible to create a "variable name" dynamically inside of a loop, while accessing another variable name dynamically inside of the loop provided the information given above (just made up code on the spot).
// psuedo code for something I'm asking is possible
for( i = 0; i < 10; i++)
{
// create BackyardObject with generic name, while appending "i" to
// variable name, and accessing other object variables
BackyardObject backyardObject'i'
= new backyardObject(cat'i', dog'i', goat'i', piglet'i');
}
While I understand that I could create additional arrays and lists to store objects and then use those, I was just seeing if it was possible to get variable names dynamically. I wasn't sure if it was entirely possible, that's why I asked the question. I know that this is a strange question, but got curious after I seen this Objective-C code:
// Getting an arrayName dynamically based on loop index
for (int i = 0; i < 10; i++)
{
NSString *arrayName = [[NSString alloc] initWithFormat:@"column%d",
i];
NSArray *array = [self valueForKey:arrayName];
}
Upvotes: 1
Views: 3489
Reputation: 1499810
Objects don't have names... what you're talking about is variables. And rather than having lots of variables with numbers as suffixes, you'd be better using collections - arrays, or lists, or whatever. Then you can do:
// Or use arrays...
List<Cat> cats = new List<Cat>();
cats.Add(new Cat(...)); // Add the cats however you want to set them up
// Ditto dogs, goats etc
List<BackyardObject> backyardObjects = new List<BackyardObject>();
for (int i = 0; i < 10; i++)
{
backyardObjects.Add(new BackyardObject(cats[i], dogs[i],
goats[i], piglets[i]));
}
I assume you're fairly new to C# - I suggest you look at arrays and collections in whatever you're learning from.
Upvotes: 8