Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Method overloading

1 view
Skip to first unread message

pagerintas pritupimas

unread,
May 12, 2008, 6:58:17 AM5/12/08
to
Not that this is a real-life problem but how would you call a "second" Foo
method ?

using System;

public class Boo<T>
{
public void Foo(int index)
{
Console.WriteLine("Foo(int)");
}

public void Foo(T key)
{
Console.WriteLine("Foo(T)");
}
}

internal static class Program
{
private static void Main()
{
Boo<int> boo = new Boo<int>();
boo.Foo(0);
}
}


Marc Gravell

unread,
May 12, 2008, 7:07:21 AM5/12/08
to
Take away the compiler's ability to know it as an integer:

private static void Main()
{
Boo<int> boo = new Boo<int>();
boo.Foo(0);

CallFooByKey(boo, 0);
}
static void CallFooByKey<T>(Boo<T> boo, T key)
{
boo.Foo(key);
}

Marc Gravell

unread,
May 12, 2008, 7:20:01 AM5/12/08
to
I should note that in C# 3 you can make this slightly more intuitive via
"extension methods" - but it is also better to avoid it by naming the
methods differently to begin with (even the language spec highlights
this as a problem scenario, best avoided...)

private static void Main()
{
Boo<int> boo = new Boo<int>();
boo.Foo(0);

boo.FooByKey(0);
}
public static void FooByKey<T>(this Boo<T> boo, T key)
{
boo.Foo(key);
}

DSK Chakravarthy

unread,
May 12, 2008, 9:05:32 AM5/12/08
to
This is really a tricky situation. but in real time, you will get to know
the object by specific entity. anyhow, if you want to eliminate the
confusion between the first method and second method, i recommend the
following suggtion.

public void foo(T key)
{
if (key.GetType().Equals(typeof(int)))
foo((int)key);
else
Console.WriteLine("Foo(T)");
}

HTH


"pagerintas pritupimas" <o...@com.net> wrote in message
news:uNwGf7B...@TK2MSFTNGP05.phx.gbl...

0 new messages