Method overloading

  • Thread starter Thread starter pagerintas pritupimas
  • Start date Start date
P

pagerintas pritupimas

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);
}
}
 
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);
}
 
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);
}
 
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
 
Back
Top