CSharp examples for Custom Type:Generics
Generics express reusability with a "template" that contains "placeholder" types.
A generic type declares type parameters-placeholder types to be filled in by the consumer of the generic type.
type Stack<T>, designed to stack instances of type T.
Stack<T> declares a single type parameter T:
public class Stack<T> { int position; T[] data = new T[100]; public void Push (T obj) => data[position++] = obj; public T Pop() => data[--position]; }
We can use Stack<T> as follows:
var stack = new Stack<int>(); stack.Push (5); stack.Push (10); int x = stack.Pop(); // x is 10 int y = stack.Pop(); // y is 5 public class Stack<T> { int position; T[] data = new T[100]; public void Push (T obj) => data[position++] = obj; public T Pop() => data[--position]; }
Stack<T> is an open type, whereas Stack<int> is a closed type.