#324 – A Generic Class Can Have More than One Type Parameter

A generic class includes one or more type parameters that will be substituted with actual types when the class is used.  If the class has more than one type parameter, all parameters must be substituted when the class is used.

Here’s an example of a generic class that stores two objects, each having its own type.

    public class ThingContainer<TThing1, TThing2>
    {
        private TThing1 thing1;
        private TThing2 thing2;

        public void SetThings(TThing1 first, TThing2 second)
        {
            thing1 = first;
            thing2 = second;
        }

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

We can use this class as follows:

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

            ThingContainer<Dog, DateTime> cont2 = new ThingContainer<Dog, DateTime>();
            cont2.SetThings(new Dog("Kirby", 14), new DateTime(1998, 5, 1));
            Console.WriteLine(cont2.DumpThings());      // Kirby (14 yrs), 5/1/1998 12:00:00 AM
Advertisements