What are Generics?
Generics is a mechanism offered by the Common Language Runtime (CLR) and programming languages that provide one form of code re-use and algorithm re-use.
Advantages of Generics
- Type Safe
- Better Performance
Let us see how we can implement Generics in our code.
I’ve created a class MyGenericSample which has a method ShowMessage that takes two parameters of which one is a Known Type string argument and another being a generic type mentioned as T. Remember defining it in <> before you use.
- public void ShowMessage<T>(string msg, T value)
- {
- Console.WriteLine("{0}: {1}", msg, value);
- }
I’ve overloaded ShowMessage method with three parameters of which one is a Known Type string argument and another two being generic types mentioned as Type1 and Type2.
- public void ShowMessage<Type1, Type2>(string msg, Type1 firstParameter, Type2 secondParameter)
- {
- Console.WriteLine("{0}: {1} {2}", msg, firstParameter, secondParameter);
- }
Now let’s see how they behave when they are called.
- static void Main(string[] args)
- {
- MyGenericSample sample = new MyGenericSample();
- sample.ShowMessage < int > ("My Pincode", 500068);
- sample.ShowMessage < string > ("My City", "Hyderabad");
- sample.ShowMessage < char > ("Gender", 'M');
-
- sample.ShowMessage < string, string > ("Full Name", "Sridhar", "Sharma");
- Console.ReadLine();
- }
Complete code - using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace GenericsSample
- {
- public class MyGenericSample
- {
- public void ShowMessage < T > (string msg, T value)
- {
- Console.WriteLine("{0}: {1}", msg, value);
- }
- public void ShowMessage < Type1, Type2 > (string msg, Type1 firstParameter, Type2 secondParameter)
- {
- Console.WriteLine("{0}: {1} {2}", msg, firstParameter, secondParameter);
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- MyGenericSample sample = new MyGenericSample();
- sample.ShowMessage < int > ("My Pincode", 500068);
- sample.ShowMessage < string > ("My City", "Hyderabad");
- sample.ShowMessage < char > ("Gender", 'M');
-
- sample.ShowMessage < string, string > ("Full Name", "Sridhar", "Sharma");
- Console.ReadLine();
- }
- }
- }
Output Conclusion
Generics makes the life of developers easy, since they offer Type Safe and there is a performance increase compared with non-generic types.