Here is a fun one.... read the following, and guess the output
class Program
{
static void Main(string[] args)
{
b test2 = new b();
a test1 = test2;
//guess the output
print(test1);
print(test2);
Console.ReadLine();
}
public static void print(b p1)
{
Console.WriteLine(string.Format("{0}, {1}, {2}", p1.Name, p1.age.ToString(), p1.GetType().ToString()));
}
public static void print(a p1)
{
Console.WriteLine(p1.Name + " " + p1.GetType().ToString() );
}
}
class a
{
public string Name = "dave";
}
class b : a
{
public int age = 25;
public b()
{
this.Name = "Dave 2";
}
}
come on guess it, before you run it! :)
Ok here is the output: (it was not what i expect or wanted)
Note that the first print, for test1, uses print(a) (which i do not agree with), and has a type of b (which I do agree with). This would suggest that the method overload is mapped at compile time. Sofar the only work around i have found is to create a new static class called p and move the print methods into this, now you can use reflection to call the right method depending on its runtime type:
//in the main method
p proc = new p();
MethodInfo mi= proc.GetType().GetMethod("print", new Type[] {t});
mi.Invoke(null, new object[] { test1 });
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5