Luna Tech

Tutorials For Dummies.

C# Generics

2021-12-04


0. What are Generics?

Objective

Help us decouple the logic from data types, so we can design classes and methods in a more generic way.

E.g., this Equals method can only compare int data types.

class Compare {
  public static bool Equals(int data1, int data2){
    return data1 == data2;
  }
}

By using generics, we can specify the data type while using this class and make the code more reusable.

class Compare {
  public static bool Equals<T>(T data1, T data2){
    return data1 == data2;
  }
}

Generics vs Generic Collections

Generic is a concept, Generic Collection is one of the implementations of the concept.

Generic classes are extensively used by collection classes in System.Collections.Generic namespace.

Generic Collection Example

List<string> s = new List<string>();

1. When to use Generics?

Why not just use System.Object type?

You might ask, if we want to make the method working for different data types, why not just make use of the object type?

class Compare {
  public static bool Equals(object data1, object data2){
    return data1 == data2;
  }
}

Problems:

boxing and unboxing

Use case

When you want to make your code type independent as well as type safety.

We can use generics for method, class, structure or interface.


2. Pros and Cons

Among the benefits of generics are increased code reusability and type safety.

Advantages

Reusability

Type Safety

Efficiency

Disadvantages

Complexity and Overhead