Introduction
I would like to introduce generic method overloading.
It would be good for you to already understand generics in C# but if not then please visit the following link.
Basics of Generic Classes in C#
First we will understand simple overloading then move towards generic overloading.
Steps and code
Add the following class to the project:
- public class SimpleClass
- {
- public void GetData(int x)
- {
- Console.WriteLine("INSIDE GetData and Datetype:" + x.GetType().Name);
- }
-
- public void GetData(string xStr)
- {
- Console.WriteLine("INSIDE GetData and Datetype:" + xStr.GetType().Name);
- }
- }
Program.cs
- class Program
- {
- static void Main(string[] args)
- {
- SimpleClass o = new SimpleClass();
- o.GetData(345);
- o.GetData("Devesh is testing the code");
- Console.ReadKey();
- }
- }
Running the Code
The following will be the output:
Understanding the code
We have created the GetData function with overloaded functions having integer and string parameters.
When we passed an integer to the method first GetData (int x ) is called else if we passed a string then GetData(string xStr) is called.
Now we have a basic knowledge of method overloading.
Let us move towards Generic Method Overloading.
Now we are updating the GetData() method as a generic method.
- public void GetData<T>(T obj)
- {
- Console.WriteLine("INSIDE GetData<T>,"+ obj.GetType().Name);
- }
The following would be the complete code:
- public class SimpleDemoClass
- {
- public void GetData<T>(T obj)
- {
- Console.WriteLine("INSIDE GetData<T>,"+ obj.GetType().Name);
- }
- public void GetData(int x)
- {
- Console.WriteLine("INSIDE GetData" + x.GetType().Name);
- }
- public void GetxNextData<T>(T obj)
- {
- GetData(obj);
- }
- }
Program.cs
- class Program
- {
- Static void Main(string[] args)
- {
- SimpleDemoClass sobj = new SimpleDemoClass();
- sobj.GetData("data is for testing by-Devesh");
- sobj.GetData(95);
- sobj.GetxNextData(1234);
- Console.ReadKey();
- }
- }
Running code
Understanding the code.
- When we called sobj.GetData("data is for testing by-Devesh");
- Getdata<T>(T obj) is called. Because we are passing a string and this is implicitly an object
- When we called sobj.GetData(95);, GetData(int x ) is called because we are passing an integer to the GetData method.
- During runtime, the compiler decides to invoke the best sutiable method to be invoked
Conclusion
Here we learned the basics of generic method overloading.