Answer: Yes, we can overload a generic methods in C# as we overload a normal method in a class.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; class GenericMethodOverloading { //Overloaded generic method with one parameter public void CustomPrint(T value) { Console.WriteLine("In overloaded one parameter generic function!"); Console.WriteLine("Input is : " + value); } //Overloaded generic method with two parameter public void CustomPrint<X,Y>(X xval, Y yval) { Console.WriteLine("In overloaded two parameters generic function!"); Console.WriteLine("Input is : " + xval+yval); } //Overloaded generic method with Specific type. public void CustomPrint() { Console.WriteLine("In overloaded with empty parameter generic function!"); Console.WriteLine("Input is : " +"Default"); } } namespace Test { class Sample { static void Main(string[] args) { GenericMethodOverloading obj = new GenericMethodOverloading(); obj.CustomPrint(5); obj.CustomPrint("Interview sansar.com"); obj.CustomPrint("Interview sansar.com :"+ 5); } } } |
Sub Question:
Q- In below example which function will get called? OR
Q- If we overload generic method in C# with specific data type which one would get called?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
class GenericMethodOverloading { //Overloaded generic method with one parameter public void CustomPrint(T value) { Console.WriteLine("In Generic function!"); Console.WriteLine("Input is : " + value); } //Overloaded generic method with Specific type. public void CustomPrint(int value) { Console.WriteLine("In normal function!"); Console.WriteLine("Input is : " + value); } } namespace Test { class Sample { static void Main(string[] args) { GenericMethodOverloading obj = new GenericMethodOverloading(); obj.CustomPrint(5); } } } |
Answer: Function with specific data type i.e int will be called. Compiler always prefer method with specific data type before generic method having same argument in C#.
Output:
In normal function!
Input is: 5