Csharp/CSharp Tutorial/Generic/Generic Class
A simple generic class
T is a type parameter that will be replaced by a real type when an object of type Gen is created.
<source lang="csharp">using System;
class Gen<T> {
T ob; public Gen(T o) { ob = o; } public T getob() { return ob; } public void showType() { Console.WriteLine("Type of T is " + typeof(T)); }
}
class MainClass {
public static void Main() { Gen<int> iOb = new Gen<int>(102); iOb.showType(); int v = iOb.getob(); Console.WriteLine("value: " + v); Console.WriteLine(); Gen<string> strOb = new Gen<string>("Generics add power."); strOb.showType(); string str = strOb.getob(); Console.WriteLine("value: " + str); }
}</source>
A simple generic class with two type parameters: T and V
<source lang="csharp">using System;
class TwoGen<T, V> {
T ob1; V ob2; public TwoGen(T o1, V o2) { ob1 = o1; ob2 = o2; } public void showTypes() { Console.WriteLine("Type of T is " + typeof(T)); Console.WriteLine("Type of V is " + typeof(V)); } public T getT() { return ob1; } public V getV() { return ob2; }
}
class MainClass {
public static void Main() { TwoGen<int, string> tgObj = new TwoGen<int, string>(1, "A"); tgObj.showTypes(); int v = tgObj.getT(); Console.WriteLine("value: " + v); string str = tgObj.getV(); Console.WriteLine("value: " + str); }
}</source>
Type of T is System.Int32 Type of V is System.String value: 1 value: A
Generic Pair
<source lang="csharp">using System; using System.Collections.Generic; using System.ruponentModel;
public sealed class Pair<TFirst, TSecond>: IEquatable<Pair<TFirst, TSecond>>{ private readonly TFirst first; private readonly TSecond second; public Pair(TFirst first, TSecond second) { this.first = first; this.second = second; } public TFirst First { get { return first; } } public TSecond Second { get { return second; } } public bool Equals(Pair<TFirst, TSecond> other) { if (other == null) { return false; } return EqualityComparer<TFirst>.Default.Equals(this.First, other.First) && EqualityComparer<TSecond>.Default.Equals(this.Second, other.Second); } public override bool Equals(object o) { return Equals(o as Pair<TFirst, TSecond>); } public override int GetHashCode() { return EqualityComparer<TFirst>.Default.GetHashCode(first) * 37 + EqualityComparer<TSecond>.Default.GetHashCode(second); } }</source>