Click here to Skip to main content
15,867,979 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
Hi All,

Quick question:

public class A<br />
{<br />
public virtual void F() {}<br />
}<br />
public class B : A<br />
{<br />
public virtual void F(int i=10) {}<br />
}<br />
<br />
A a = new B();<br />
a.F();


Which 'F' gets called - or does it not compile, warning about an ambiguity? Or is this a dozy question?
Posted
Updated 13-Apr-10 4:26am
v2

I tried the code at home, the answer is your code will compile, and there is no ambiguity! If you'd done this instead:


C#
public class B : A
{
  public <big>override</big> void F(int i=10) {}
}


It would have failed, not due to ambiguousness but because, in effect, class A doesn't have a public void F(int i) to override.

Your code will call method F in class A. As a side note, as far as the compiler is concerned B.F() doesn't exist, even though you can call it. So if you were to override, you only need to have a virtual A.F(int) and not a A.F()

I've updating my article (not the continued shameless plug!), to include the fallout from your question!
Named and Optional Arguments[^]
 
Share this answer
 
v5
Because it can't determine which version of F you're trying to call. Think about it.

You have F() - a method with no parameters, and F(int i=10) - a method that can be CALLED with no parameters.

If you call F(), which one should the compiler chose? They're essentially the same. However, if you call F(10) it knows which version to pick, but at that point, your overload is ineffectual because despite the default parameter because you must call it with a parameter in order to use it.

Your best bet is to move the combine the two and keep your optional parameter.
 
Share this answer
 
v2
public class A
{
public virtual void F()
{
Console.WriteLine("A's F()");
}
}
public class B : A
{
public virtual void F(int i=10)
{
Console.WriteLine("B's F()");
}
}

Class Program
{
static void Main(String[]args)
{
A a = new B();
a.F();
}

Answer:A's F()
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900