Search code examples
c#oopclassclass-design

Class Structure for a list Class?


I am looking for some class structure help. Lets say I have a class called Dog holds information about the dog (name, weight, type) but because there could be multiple dogs, I would also like a class to hold all of these dogs, for use throughout my entire project. Whats the best way to go about doing this?

Just to have a DogList class, that stores the Dog class information into a public list? Allowing me to retrieve it at will?

Or should the list be a static within the original dog class? maybe in the constructor, any time someone creates a new dog, the dog gets put into the static list?

Edit: Sorry question was a bit miss leading Here is the structure I have so far, wondering if there is a better way to implement.

public class Dog
{
    public string name{get;set;}
    public int weight { get; set; }
}

public class DogFactory //not sure if thats the correct wording
{
    public List<dog> lstDogs = new List<dog>();
    public void setDogs()
    {
    Animal.Retrieve("Dog"); 
    //will retrieve a list of all dogs, with details, though this is costly to use
        foreach(Animal.Dog pet in Animal._Dogs)
        {
            Dog doggie = new doggie();
            doggie.Name = pet.Name;
            ...etc
            lstDog.add(doggie);
        }
    }
}

Solution

  • The easiest way to make a list of dogs is:

    List<Dog>

    This is a strongly-typed list of Dogs using the List<T> class from System.Collections.Generic. You can make a class of this:

    public class DogList : List<Dog>

    Though this is usually not necessary unless you want to add properties specifically to a list of Dogs and not the dogs themselves.

    UPDATE:

    You usually do not need to create a dedicated list class when using List<T>. In most cases, you can do this:

    public class DogService
    {
        public List<Dog> GetAllDogs()
        {
            var r = new Repository(); // Your data repository
            return r.Dogs.ToList();   // assuming your repository exposes a 'Dogs query'
        }
    }
    

    If you're using LINQ to get your data, you can use the ToList() extension to return a List<T>, so no need to create a class that derives from List<T>.