-
August 19th, 2013, 10:58 PM
#1
Best way to declaring multiple objects
I'm new to C# and have been reading up on Classes. In my small app, I want to instantiate a class called 'backupJob'. There is one 'operationType' member with two string values: 'local to remote server' and 'syncing both ways'. I want to create an object for one op type and then create another object for the other type.
In the demos I have seen, they always show classes created this:
Car myCar1 = new Car();
Car myCar2 = new Car();
I may end up with more than two backup jobs so I'm thinking there must be a better way to manage the object names besides myCar1 and myCar2, etc. I will want to have the ability to delete an object as well as create more objects, so is it best to keep track of these objects in an Array or possibly a Collection?
Thanks...
-
August 20th, 2013, 02:37 PM
#2
Re: Best way to declaring multiple objects
Sure, you can use collections. Consider using generic collections rather than the older Array.
If you only need to cycle through all of the cars, then a list works well.
Code:
var list = new List<Car>();
list.Add(new Car());
list.Add(new Car());
foreach(var car in list)
{
car.DoSomething();
}
If you need to access individual cars by a key, use a dictionary
Code:
var dict = new Dictionary<int, Car>();
dict.Add(1, new Car());
dict.Add(2, new Car());
var car2 = dict[2];
// Dictionaries also allow you to access the collection like a list
foreach(var car in dict.Values)
{
car.DoSomething();
}
-
August 20th, 2013, 02:42 PM
#3
Re: Best way to declaring multiple objects
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|