What are some examples of where you would use generics in C#/VB.NET and why would you want to use generics?
Simply, you declare a type or method with extra tags to indicate the generic bits:
class Foo<T> {
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<int> foo = new Foo<int>(27);
All T
s have been replaced with int
in the above. If necessary, you can restrict generic arguments with constraints:
class Foo<T> where T : struct {}
Now Foo<string>
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>
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<T> // or another type argument
You can have as many generic arguments as you need:
public struct KeyValuePair<TKey,TValue> {...}
Other things to note:
Foo<int>
is separate to that on Foo<float>
.for example:
class Foo<T> {
class Bar<TInner> {} // is effectively Bar<T,TInner>, for the outer T
}
Example 1: You want to create triple class
Class Triple<T1, T2, T3>
{
T1 _first;
T2 _second;
T3 _Third;
}
Example 2: A helper class that will parse any enum value for given data type
static public class EnumHelper<T>
{
static public T Parse(string value)
{
return (T)Enum.Parse(typeof(T), value);
}
}