#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
Advertisement

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

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

  1. Pingback: #1,029 – How to Define a Constructor in a Generic Type | 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: