Why to use Generic method if we can overload a method for multiple data types?

Answer: As we know that as a general rule, we should write generic method in C# if the method operation is same for all data type.

Or, we can say that if we have single implementation of method for all the data type.

This is true that overloading will also work here, but, we’ll miss the following.

  • Clean and readable code: only one method for all in a class.
  • Easy maintenance: in the future if we have to update/ optimize the algorithm inside the method we have to update at one place.

For example, below we have two classes i.e. one for overloaded method and one for generic method.

Now, we can easily noticed the first benefit i.e. clean and readable code.

And secondly, let’s say, we want to update text in the body of a function from “Input is:” “to Result is:” then we have to update the same in all the overloaded methods. But in the second class, we have to update at single place only. Isn’t a maintenance easy?

//Class with overloaded methods
class Console
{
    public void CustomPrint(int value)
    {        
        Console.WriteLine("Input is : " + value);
    }
    public void CustomPrint(float value)
    {
        Console.WriteLine("Input is : " + value);
    }
    public void CustomPrint(string value)
    {
        Console.WriteLine("Input is : " + value);
    }
}
//Class with a generic method
class Console
{
    public void CustomPrint(T value)
    {        
        Console.WriteLine("Input is : " + value);
    }   
}


Notes:

  • Method overloading we should use if there is different implementation of method for each data types/multiple parameters
  • In a real huge project, I have seen myself tones of duplicate code causing huge maintenance efforts and time. And of course, some of you might also have faced for the same.

Related Posts