Generics in C# allow methods and classes to be parameterized by type.
Below is an example of a generic method that swaps two values of any type:
main.cs90 chars7 lines
In this example, T
is the generic type parameter.
Now, we can use this method to swap integers:
main.cs47 chars4 lines
We can also use it to swap strings:
main.cs72 chars4 lines
And this is an example of a generic class Stack<T>
that can hold any type of object:
main.cs488 chars25 lines
We can now create a stack of integers:
main.cs130 chars6 lines
Or a stack of strings:
main.cs151 chars5 lines
gistlibby LogSnag