Skip to content
David Cumps
Exam 70-536 study notes

Generic Types

Part of my 2008 study notes for exam 70-536 (.NET Framework 2.0).

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 one 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);

You May Also Like