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:

 // A simple generic class with two type // parameters: T and V. using System; 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 getob2() {     return ob2;   } } // Demonstrate two generic type parameters. class SimpGen {   public static void Main() {     TwoGen<int, string> tgObj =       new TwoGen<int, string>(119, "Alpha Beta Gamma");     // Show the types.     tgObj.showTypes();     // Obtain and show values.     int v = tgObj.getob1();     Console.WriteLine("value: " + v);     string str = tgObj.getob2();     Console.WriteLine("value: " + str);   } }

The output from this program is shown here:

 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 passed to TwoGen when an object is created, as shown next:

 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.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net