What is Generics Use of Generics in C#

What is Generics

It's an important feature of C# language which allows you to write type-safety code. Generics are used with Classes where you can define your library methods with generic types. We have many in-build generic classes available with .NET framework such as Dictionary, List, ArrayList etc.

When to use it

On large picture, generics are useful while developing framework or complex framework per say. It allows to write one piece of code and use it irrespective type information.

Its uses -

  1. Allows you to write piece of code which applicable to may other types e.g. List<int>, List<string> both use same piece of code.

  2. Provided type safety so one don't need to worry about boxing/un-boxing or object casting. e.g List<INT> will surely be list of integer values.

  3. You can avoid casting issues such as value type to reference type.

Example

Below is simple example for generics which explains how single piece of code can be used for different types.

  1. using System;  
  2. class GenericTest < T >  
  3. {  
  4.     T myValue;  
  5.     public GenericTest(T t)  
  6.     {  
  7.         this.myValue = t;  
  8.     }  
  9.     public void Show()  
  10.     {  
  11.         Console.WriteLine(this.myValue);  
  12.     }  
  13. }  
  14. class Program  
  15. {  
  16.     static void Main()  
  17.     {  
  18.         GenericTest < int > obj1 = new GenericTest < int > (7);  
  19.         obj1.Show();  
  20.         GenericTest < string > obj2 = new GenericTest < string > ("CSharp Corner");  
  21.         obj2.Show();  
  22.     }  
  23. }  
Output will be -

7
CSharp Corner

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now