Generic Types

Overview

  • Allows you to use placeholders for parameters, which get defined later by the caller.
  • Allows for strongly typed collections, which enable compile-time checking of types.
  • Requires the developer to write generic code, which is valid for all types of T.
    • Can be avoided by using constraints on allowed types for T, demonstrated below.
    • You can only use 1 class as a constraint, but multiple interfaces.

Good practice

Examples

Generic Placeholder

class MyHolder<T> 
    //where T: struct
    //where T: MyNumber
    //where T: class
    //where T: class, IComparable
    //where T: new()
{
    private T _thing;
 
    public T Thing
    {
        get { return this._thing; }
    }
 
    public MyHolder(T thing)
    {
        this._thing = thing;
    }
}
MyHolder<int> nr = new MyHolder<int>(5);
MyHolder<string> name = new MyHolder<string>("CumpsD");
 
Console.WriteLine(nr.Thing);
Console.WriteLine(name.Thing);