Can we overload a generic method in C#?

Answer: Yes, we can overload a generic methods in C# as we overload a normal method in a class.
Example:

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?

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

Related Posts