General method overloading problem

I have the following methods:

void s<t>(int a, t b)
{
    ...
    ..
    .
}

void s<int>(int a, int b)
{
    ...
    ..
    .
}

void s<long>(int a, long b)
{
    ...
    ..
    .
}

      

when i want to use it like s<long>(10,10)

i see these overrides in the tooltip. s<long>(int a,int b);

and s<long>(int a,long b);

. But, I think I should only see s<long>(int a,long b);

.

What happened? I have visual studio 2008 sp1.

thank

Update: I tested it in Visual Studio 2010. The result is the same. Update: Seems like this is not C # visual studio.

+2


source to share


1 answer


You are trying to directly specify the type parameters you want in a generic definition, which won't work. If you want to have versions of a method that support (for the second parameter) type objects int, long, and T

, declare 2 non-generic overloading methods and one generic.

void S(int a, int b)
void S(int a, long b)
void S<T>(int a, T b)

      

Overload resolution will then call the appropriate method based on the arguments, matching non-generic versions for exact matches to int

or long

(you can get a generic version even with int

or a long

parameter if you explicitly call it with a type parameter), otherwise get a generic version.

Examples:

void S<T>(int a, T b)
{
    Console.WriteLine("generic method");
}

void S(int a, int b)
{
    Console.WriteLine("int overload");
}

void S(int a, long b)
{
    Console.WriteLine("long overload");
}

      

...

S(10, 10);
S(10, (long)10);
S(10, 10L);
S(10, 10M);
S<int>(10, 10); // uses generic
S<long>(10, 10); // uses generic & implicit conversion

      



Edit: To expand a point indicated briefly above and below in the comments line for overload int

and long

must be accurate. All other arguments will result in a generic version being chosen. If you don't have an int, but want to overload int, you will need to explicitly convert the argument before or during the method call. an ex: S(10, (int)myShort);

.

Likewise, if you have two versions of the method C

void C(Mammal m) { }
void C<T>(T t) { }

      

from

class Tiger : Mammal { }

      

The call C(new Tiger())

will result in a generic method being used. If you need an overload Mammal

for an instance Tiger

, you need a reference through the base class. For example,

Mammal m = new Tiger();
C(m); // uses mammal overload
// or 
Tiger t = new Tiger();
C((Mammal)t); // uses mammal overload

      

+2


source







All Articles