C# Generic Types

Description

A generic type declares type parameters-placeholder types to be filled in by the instance of the generic type.

Example

Here is a generic type Stack<T>, designed to stack instances of type T.

Stack<T> declares a single type parameter T:


public class Stack<T>
{//from www . j a  v  a2 s.c o  m
 int position;
 T[] data = new T[100];
 public void Push (T obj)   { data[position++] = obj;  }
 public T Pop()             { return data[--position]; }
}

Stack<int> stack = new Stack<int>();
stack.Push(5);/*  ww  w  .  ja  v a  2 s.co  m*/
stack.Push(10);
int x = stack.Pop();        // x is 10
int y = stack.Pop();        // y is 5

Stack<int> fills in the type parameter T with the type argument int.

Stack<T> is an open type, whereas Stack<int> is a closed type.

At runtime, all generic type instances are closed-with the placeholder types filled in. This means that the following statement is illegal:


var stack = new Stack<T>();   // Illegal: What is T?

unless inside a class or method which itself defines T as a type parameter:


public class Stack<T>
{/*w  ww.j a va  2 s .c  om*/
     public Stack<T> Clone()
     {
       Stack<T> clone = new Stack<T>();   // Legal
    
     }
}

Self-Referencing Generic Declarations

A type can name itself as the concrete type when closing a type argument.


public interface IEquatable<T> { bool Equals (T obj); }
//from  w ww . j  ava  2  s.  c  om
public class Balloon : IEquatable<Balloon>
{
  public string Color { get; set; }
  public int CC { get; set; }

  public bool Equals (Balloon b)
  {
    if (b == null) return false;
    return b.Color == Color && b.CC == CC;
  }
}

Static Data

Static data is unique for each closed type:


using System;//from  w ww.j ava2  s. co  m
class MyClass<T> { public static int Count; }

class Test
{
  static void Main()
  {
    Console.WriteLine (++MyClass<int>.Count);     // 1
    Console.WriteLine (++MyClass<int>.Count);     // 2
    Console.WriteLine (++MyClass<string>.Count);  // 1
    Console.WriteLine (++MyClass<object>.Count);  // 1
  }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor