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:
- performance degradation due to uncessary boxing and unboxing;
- the method will be no longer type safe, you can pass in different types for the parameters, and the code may break;
boxing and unboxing
- boxing means value type (int: 10) will be converted to object type/reference type at runtime;
- unboxing is vice versa, changing a reference type back to value type;
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
- Less code and code is more easily reused.
Type Safety
- Compiler will check the type for you, thus reduce the need of type casting and the possibility of run-time errors.
Efficiency
- No boxing and unboxing for value types.
Disadvantages
Complexity and Overhead
- Developers need to specify the type when using this method