#1,029 – How to Define a Constructor in a Generic Type

When you define a generic type, you include one or more type parameters in the declaration of the type, indicating the type of the type arguments that you specify when constructing an instance of the type.

As with other types, you can define one or more constructors in a generic type.  The constructor uses the name of the type, but without the associated type parameters.  You can, however, have constructors that accept parameters whose type is one of the type parameters.

In the example below, the second constructor makes use of the T type parameter.

    public class PileOf<T>
    {
        private List<T> thePile;

        public PileOf()
        {
            thePile = new List<T>();
        }

        public PileOf(T firstThingInPile)
        {
            thePile = new List<T>();
            thePile.Add(firstThingInPile);
        }

        public void AddThing(T thing)
        {
            thePile.Add(thing);
        }
    }

We can then use this type as follows:

            PileOf<Dog> intPile = new PileOf<Dog>(new Dog("Bowser"));
            intPile.AddThing(new Dog("Fido"));

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment