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 1 class as a constraint, but multiple interfaces.
Good practice
- Generics FAQ: Best Practices - MSDN document describing possible problems/solutions with generics.
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
ArrayList Class
Resizeable, unordered, index-based collection. Suffers from boxing/unboxing when working with value types. Implements IEnumerator, allowing foreach…
BinaryReader Class and BinaryWriter Class
Used to read and write binary data from streams. Call the correct Read methods when using a BinaryReader.
BitArray Class
Contains an array of true/false values. Resizable through the Length property. Supports bitwise operations.



