#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

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

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

  1. Pingback: #1,135 – Overloading a Generic Class | 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: