#1,039 – Deriving from a Generic Class

A generic class includes one or more type parameters, allowing you to later declare a variable using a constructed type by specifying type arguments for each type parameter.

If you have an existing generic class, you can define a new class that inherits from the generic class.

Assume that we have a List<T> type, i.e. we can construct the type as follows:

            List<int> someInts = new List<int>();

We can also define a new class that inherits from List<T> and makes use of its type parameter as follows:

    public class ListPlus<T> : List<T>
    {
        public void AddTwoItems(T thing1, T thing2)
        {
            base.Add(thing1);
            base.Add(thing2);
        }
    }

We can now construct the new type by providing a type argument.

            ListPlus<Dog> dogs = new ListPlus<Dog>();
            Dog fido = new Dog("Fido");
            Dog bowser = new Dog("Bowser");
            dogs.AddTwoItems(fido, bowser);
Advertisements