C# Generic Types

In this chapter you will learn:

  1. What are Generic Types
  2. Example for a generic stack
  3. Self-Referencing Generic Declarations
  4. Static Data

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>
{// w  ww.j  av a 2s.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);//from   ww w  .j  a va  2s .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  w  w. ja va  2s. c  o m
     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); }
/*www.  j a  v  a2  s .c  o  m*/
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 www  .ja v a2  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.

Next chapter...

What you will learn in the next chapter:

  1. What are Generic Methods
  2. Example generic method
Home »
  C# Tutorial »
    C# Types »
      C# Generics
C# Generic Types
C# Generic Methods
C# default Generic Value
C# Generic Constraints
C# Subclassing Generic Types
C# Generic Delegate
C# Type Parameters