CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2013
    Posts
    2

    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...

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    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();
    }

  3. #3
    Join Date
    Aug 2013
    Posts
    2

    Re: Best way to declaring multiple objects

    Thanks!!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured