In C#, which Console.WriteLine() would be hit?
Without consulting your compiler, take a look at the code and then vote your answer.
public class A
{
public void Bar(int n)
{
Console.WriteLine("A.Bar");
}
}
public class B : A
{
public void Bar(double n)
{
Console.WriteLine("B.Bar");
}
}
class Program
{
static void Main(string[] args)
{
B b = new B();
b.Bar(5);
}
}
Vote your answer now before you read any further.
At the time of writing this the general consensus was wrong. Note - I was also wrong when I took a guess at what the answer is.
The answer is that B.Bar will be hit and not A.Bar
My theory behind why this happens is that I think that C# walks the inheritance tree from the outer class inwards and each time that it finds a matching function name it then checks to see if all of the parameters can be cast to the first method that it finds. If so, it then uses that method.
With the help of a friend, I then tested this on Java. It turns out that Java does not behave in this manner. The Java compiler, I'm guessing takes 2 walks of the inheritance tree. The first time it looks for an exact match. The second time it attempts to do a cast. So the answer for a Java compiler would be a print of A.Bar. However, this question was asking about C#.
Here are the results of the poll
EDIT: Name mangling - that's how it does it in Java and C++. It creates a unique name for each function call based on its function name and the parameter types. I just remembered that.
This is kind of counter-intuitive if you are indeed more familiar with java and the like, but also remember that C# has the virtual and new method modifiers to declare explicitly what you intend to do with a subclassed (and effectively overridden) method.
ReplyDeleteI agree it is counter-intuitive and not what most of us would expect as seen by the number of incorrect guesses. At least if we're aware of it then it shouldn't bite us.
ReplyDelete