Edward Tanguay
Edward Tanguay

Reputation: 193302

How can I use generics to put this method in the parent class?

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

Upvotes: 1

Views: 141

Answers (2)

Skurmedel
Skurmedel

Reputation: 22149

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.

Upvotes: 5

Matthew Flaschen
Matthew Flaschen

Reputation: 284796

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

Upvotes: 6

Related Questions