In an earlier post Microsoft Dotnet Interview Questions 2012, question no. 10 was about benefits of generics. In this post I would answer that.
Main benefits of Generics
Generics typically provides a lot of performance and code safety benefits which are listed below:
- Generics enforce Type Safety: Type safety means that only object compatible with specified types will be used in the generic algorithm. This helps to write a code which is less prone to errors. When generics are used, compiler knows that only a specific type will be encountered. For example, a foreach loop can be easily used on a List
because it contains only strings. If we had used a for loop as well, it would work fine. But consider if List was not generic and it might contain integers as well, then it would have made the code prone to errors.
- Performance boost: Usage of generics boost the performance of the system, since it avoids a lot of Boxing and Unboxing process. This feature is a positive side effect of type safety as well. Traditionally, if some algorithm had to be written which should work on multiple data types, it would be based on Object type. It meant if user ran the algorithm for value type, then a lot of boxing and unboxing operations would happen in the algorithm. Since generics are type safe, and are not based on Object type, these operations are avoided and performance is boosted.
- Clean code: Again a positive side effect of Type safety, since the code works on a single data type, there is no code for casting and reverse casting of variables. That ends up with cleaner source code.
So we have seen that the major benefit of using generics is that they provide type safety which in turns boosts the performance.
Any questions comments are welcome.