What are Generics? How do you write a Generic method that takes two type arguments and return a value?
- Generics introduce the concept of passing types as parameters.
- These make it possible to design classes and methods which can be reused for all types, and the type is deferred until the class is instantiated at the client code.
- Generics provide code-reuse, type safety and performance
- Most common application of Generics are the Collection types (IEnumerable, List ..) which are present in the System.Collections.Generic namespace
- One can create own generic interfaces, events, delegates or methods.
- Some generic types might also involve constraints on the type that is being passed to the generic types.
Program p = new Program();
// ERROR: Operator '+' cannot be applied to operands of type 'T' and 'T'
// cast to dynamic because compiler doesn't know the type
// to overload the + operator
public T Add<T>(T a, T b)
return (dynamic)a + (dynamic)b;
Posted May 14, 2021