When two overloads of a method in a generic class are the same (have identical type arguments) as a result of the generic type you specified, which method is called?

For example, given a generic class named “Generic” that has an overloaded method “Add”:

public class Generic<T>
{
    public void Add( T item )
    {
        Console.WriteLine( "Add T" );
    }
    public void Add( string item )
    {
        Console.WriteLine( "Add string" );
    }
}

If you instantiate the “Generic” class with the ‘string’ type:

Generic<string> genString = new Generic<string>();

What happens when you call the “Add” method? 

genString.Add( "3" );

The Answer

The question arises because the “Generic” class already has an “Add” method defined to accept a string argument.  When you instantiate the “Generic” class with a string type, now there are two “Add” methods which accept a string.

If a generic class has identical method overloads, the method with the explicitly defined type will execute.

So in this example, the method with the string argument will run:

public void Add( string item )

Sample Program

Here is a simple console program that demonstrates this:

using System;

namespace GenericDupOverload
{
    class Program
    {
        static void Main( string[] args )
        {
            Generic<int> genInt = new Generic<int>();
            genInt.Add( 3 );
            genInt.Add( "3" );
            Generic<string> genString = new Generic<string>();
            genString.Add( "3" );
            Console.ReadLine();
        }
    }
    public class Generic<T>
    {
        public void Add( T item )
        {
            Console.WriteLine( "Add T" );
        }
        public void Add( string item )
        {
            Console.WriteLine( "Add string" );
        }
    }
}

Console Output

And the console output is:

Add T
Add string
Add string

Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot