Why use Generics in C# dot net


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:

  1. 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.
  2. 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.
  3. 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.

DZoneDeliciousLinkedInRedditTechnorati FavoritesStumbleUponShare


  1. Why use generics in C# dot net | Tech Samosa…

    You’ve been kicked (a good thing) – Trackback from DotNetKicks.com…

  2. Micle says:

    Great information it is very useful :)

  3. Imran says:

    Thanks alot.my problem has been solved.

Leave a Reply

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