CSharp/C# Tutorial - C# Type Parameters

Type parameters can be introduced in the declaration of classes, structs, interfaces, delegates, and methods.

Other constructs, such as properties, cannot introduce a type parameter, but can use one.


For example, the property Value uses T:

public struct Nullable<T> {
    public T Value { 

multiple parameters

A generic type or method can have multiple parameters.

For example:

class Dictionary<TKey, TValue> {...} 

To instantiate:

Dictionary<int,string> myDic = new Dictionary<int,string>(); 


var myDic = new Dictionary<int,string>(); 

Generic type names and method names can be overloaded as long as the number of type parameters is different.

For example, the following two type names do not conflict:

class A<T> {} 
class A<T1,T2> {} 

The default Generic Value

The default keyword can be used to get the default value given a generic type parameter.

The default value for a reference type is null, and the default value for a value type is the result of bitwise-zeroing the value type's fields:

static void MyMethod<T> (T[] array) { 
    for (int i = 0; i < array.Length; i++) {
       array[i] = default(T);