A Generic Class with Two Type Parameters

You can declare more than one type parameter in a generic type. To specify two or more type parameters, simply use a comma-separated list. For example, the following TwoGen class is a variation of the Gen class that has two type parameters:


using System;
using System.IO;
namespace ConsoleApplication1
    class TwoGen<T, V>
        T ob1;
        V ob2;
        // Notice that this constructor has parameters of type T and V.
        public TwoGen(T o1, V o2)
            ob1 = o1;
            ob2 = o2;
        // Show types of T and V.
        public void showTypes()
            Console.WriteLine("Type of T is " + typeof(T));
            Console.WriteLine("Type of V is " + typeof(V));
        public T getob1()
            return ob1;
        public V GetObj2()
            return ob2;
    // Demonstrate two generic type parameters.
    class SimpGen
        static void Main()
            TwoGen<int, string> tgObj =
            new TwoGen<int, string>(119, "Alpha Beta Gamma");
            // Show the types.
            // Obtain and show values.
            int v = tgObj.getob1();
            Console.WriteLine("value: " + v);
            string str = tgObj.GetObj2();
            Console.WriteLine("value: " + str);



<em>Type of T is System.Int32
Type of V is System.String
value: 119
value: Alpha Beta Gamma

Notice how TwoGen is declared:

class TwoGen<T, V> {

It specifies two type parameters: T and V, separated by a comma. Because it has two type parameters, two type arguments must be specified when a TwoGen object is created, as shown here:

TwoGen<int, string> tgObj = new TwoGen<int, string>(119, "Alpha Beta Gamma");

In this case, int is substituted for T and string is substituted for V. Although the two type arguments differ in this example, it is possible for both types to be the same. For example, the following line of code is valid:

TwoGen<string, string> x = new TwoGen<string, string>("Hello", "Goodbye");

In this case, both T and V would be of type string. Of course, if the type arguments were always the same, then two type parameters would be unnecessary.


You may also like...