471,350 Members | 2,049 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,350 software developers and data experts.

Method overloading

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<intboo = new Boo<int>();
boo.Foo(0);
}
}
Jun 27 '08 #1
3 1004
Take away the compiler's ability to know it as an integer:

private static void Main()
{
Boo<intboo = new Boo<int>();
boo.Foo(0);
CallFooByKey(boo, 0);
}
static void CallFooByKey<T>(Boo<Tboo, T key)
{
boo.Foo(key);
}
Jun 27 '08 #2
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<intboo = new Boo<int>();
boo.Foo(0);
boo.FooByKey(0);
}
public static void FooByKey<T>(this Boo<Tboo, T key)
{
boo.Foo(key);
}
Jun 27 '08 #3
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" <or*@com.netwrote in message
news:uN*************@TK2MSFTNGP05.phx.gbl...
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<intboo = new Boo<int>();
boo.Foo(0);
}
}
Jun 27 '08 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by John Smith | last post: by
18 posts views Thread by Daniel Gustafsson | last post: by
10 posts views Thread by Mihai Osian | last post: by
11 posts views Thread by placid | last post: by
5 posts views Thread by Andreas Schmitt | last post: by
1 post views Thread by Zach | last post: by
10 posts views Thread by Matthew | last post: by
reply views Thread by XIAOLAOHU | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.