Method overloading

  • Thread starter pagerintas pritupimas
  • 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);
}
}
 
M

Marc Gravell

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);
}
 
M

Marc Gravell

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);
}
 
D

DSK Chakravarthy

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top