views:

75

answers:

2

I have a number of plural item classes which each have a collection of singular item classes, like this:

public class Contracts : Items
{
        public List<Contract> _collection = new List<Contract>();
        public List<Contract> Collection
        {
            get
            {
                return _collection;
            }
        }
}

public class Customers: Items
{
        public List<Customer> _collection = new List<Customer>();
        public List<Customer> Collection
        {
            get
            {
                return _collection;
            }
        }
}

public class Employees: Items
{
        public List<Employee> _collection = new List<Employee>();
        public List<Employee> Collection
        {
            get
            {
                return _collection;
            }
        }
}

I can imagine I could use generics to put this up into the parent class. How could I do this, I imagine it would look something like this:

PSEUDO-CODE:

public class Items
{
        public List<T> _collection = new List<T>();
        public List<T> Collection
        {
            get
            {
                return _collection;
            }
        }
}
+6  A: 

That's completely right, except you also want a <T> after Items:

public class Items<T>
{
        public List<T> _collection = new List<T>();
        public List<T> Collection
        {
            get
            {
                return _collection;
            }
        }
}

To instantiate:

Items<Contract> contractItems = new Items<Contract>();
Matthew Flaschen
+5  A: 

Yes, although Items would have to be generic as well.

public class Items<TItem>
{
    private IList<TItem> _items = new List<TItem>();
    public IList<TItem> Collection
    {
        get { return _items; }
    }
    // ...
 }

It would probably make sense to have Items inherit from IEnumerable<TItem> too.

Skurmedel
What would that get me if Items inherited from IEnumerable, could I somehow just use Items in a foreach loop? I was looking for a way to do that.
Edward Tanguay
Yes, you would be able to do foreach (strictly you only need to have a GetEnumerator but you might as well properly implement IEnumerable<TItem>).
Matthew Flaschen