What is Generics in C# Programming?

(Last Updated On: March 14, 2017)

Answer of generics in C# interview questions should includes generics with example program in c# and its advantages.

Answer: Generics in C# programming allow us to design classes and methods decoupled from the data types.Here generics means, the same class or same method should be able to handle any data types i.e. int, float, double and string etc.

Use of generics type provides code re-usability. Meaning, we don’t need to write multiple methods for same operation for different data types and should consider writing generic classes or generic method in C# programming.

Decoupling means, a method operation is independent of data types. We can supply any data types to parameter list of a method e.g. int , float and string etc.

For example, below function is tightly coupled with int data type, hence, it cannot perform operation on string or any other data types.

 

 

If we want to operate string data type on this function we need to overload this method for string data type i.e.

Similarly for other data types also we need to overload the same function. Hence, as a conclusion, we would be writing duplicate functions. And that’s where generic method comes into picture to avoid duplicates. Write on generic method that handle all data types.

Here is the method that can handle any data types called generic method in C# programming.

 

Example without generic method in c# :
 

Example with generic method in c# :
 

The same rule is applied to Generic class in C# Programming

Example source code:

 

NOTES:

1) Advantage of using Generic method/ Class

  • Avoid duplicate codes and make classes readable.
  • Easy maintenance: if we want to change/update algorithms or class we need to update at one place only.

2)In the Generic method declaration , public static void CustomPrint<T>(T value). T is just a place holder. We can write any letter e.g. X, Y or Z and it should work.

3) Common use of generics is to create collections classes that work on multiple data types.

 

To Focus:

In an interview you may be asked to write the declaration and calling convention syntax of generic method or generic class in C# programming. So, just notice the same in the above examples.