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();
Console.WriteLine(p.Add<int>(5, 7));
Console.WriteLine(p.Add<double>(4.5, 8.3));
Console.WriteLine(p.Add<string>("Alice", "Bob"));

// 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;
}

output:
12
12.8
AliceBob

C# Concepts Posted May 14, 2021

You can now show your support. 😊

We use cookies to provide you with a great user experience, analyze traffic and serve targeted promotions.   Learn More   Accept