#1,027 – Type Parameters vs. Type Arguments in a Generic Class

generic class is a class that takes one or more type parameters, which it then uses in the definition of the class.  It can be thought of as a template for a class.

Type parameters are used in the definition of the type.  In the code below, T1 and T2 are type parameters.

    public class ThingContainer<T1, T2>
    {
        private T1 thing1;
        private T2 thing2;

        public void SetThings(T1 first, T2 second)
        {
            thing1 = first;
            thing2 = second;
        }

        public string DumpThings()
        {
            return string.Format("{0}, {1}", thing1.ToString(), thing2.ToString());
        }
    }

You provide a type argument for each type parameter when you declare an instance of the generic type, constructing the type.  In the sample code below, string and int are the type arguments that map to the T1 and T2 type parameters.

            ThingContainer<string, int> cont1 = new ThingContainer<string, int>();
            cont1.SetThings("Hemingway", 1899);
            Console.WriteLine(cont1.DumpThings());      //  Hemingway, 1899
Advertisements