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
  • 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

Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *