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
Hi, I am trying to do this exact same thing in VB.NET but find the opposite i.e. the method with a paramter typed as T is always the one to get called. Any ideas?
Unfortunately C# and VB.NET differ in many subtle ways. Apparently you have discovered another. Thanks for commenting!
Actually, I was wrong. I was doing something slightly different and I suspect the same thing will happen in C#. I was creating a variable of type T inside the generic class then passing that to the overloaded method. In this case, as I said, the overload with parameter of type T is called. If I do something more like you are doing here, I get the same results.
using System;
namespace GenericDupOverload
{
class Program
{
static void Main( string[] args )
{
Generic genInt = new Generic();
genInt.Add( 3 );
genInt.Add( “3” );
Generic genString = new Generic();
genString.Add( “3” );
Console.ReadLine();
}
}
public class Generic
{
public void Add( T item )
{
Console.WriteLine( “Add T” );
}
public void Add( string item )
{
Console.WriteLine( “Add string” );
}
}
}