Simply, you declare a type or method with extra tags to indicate the generic bits:
class Foo {
public Foo(T value) {
Value = value;
}
public T Value {get;private set;}
}
The above defines a generic type Foo
"of T
", where the T
is provided by the caller. By convention, generic type arguments start with T. If there is only one, T
is fine - otherwise name them all usefully: TSource
, TValue
, TListType
etc
Unlike C++ templates, .NET generics are provided by the runtime (not compiler tricks). For example:
Foo foo = new Foo(27);
All T
s have been replaced with int
in the above. If necessary, you can restrict generic arguments with constraints:
class Foo where T : struct {}
Now Foo
will refuse to compile - as string
is not a struct (value-type). Valid constraints are:
T : class // reference-type (class/interface/delegate)
T : struct // value-type except Nullable
T : new() // has a public parameterless constructor
T : SomeClass // is SomeClass or inherited from SomeClass
T : ISomeInterface // implements ISomeInterface
Constraints can also involve other generic type arguments, for example:
T : IComparable // or another type argument
You can have as many generic arguments as you need:
public struct KeyValuePair {...}
Other things to note:
- static members etc are defined per generic type combination - so a static field on
Foo
is separate to that on Foo
.
- methods can be generic too - try to avoid using the same names as the class uses, as you won't be able to disambiguate
- nested types inherit the generic types from their parents
for example:
class Foo {
class Bar {} // is effectively Bar, for the outer T
}