Really simple to replicate, the output is bizarre;
Expected output is "bbb bbb" Actual output is "aaa bbb"
Has anyone got any MSDN explanation of this behaviour? I couldn't find any.
((a)new b()).test();
new b().test();
public class a
{
public virtual void test(string bob = "aaa ")
{
throw new NotImplementedException();
}
}
public class b : a
{
public override void test(string bob = "bbb ")
{
HttpContext.Current.Response.Write(bob);
}
}
There are no default parameters in C. One way you can get by this is to pass in NULL pointers and then set the values to the default if NULL is passed. This is dangerous though so I wouldn't recommend it unless you really need default parameters.
A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.
C allows functions with a variable number of arguments (called variadic functions) through the use of a set of macros defined in the stdarg. h header: va_start() , va_copy() , va_arg() and va_end() that allow you to scan the list of arguments.
No you cannot overload functions on basis of value of the argument being passed, So overloading on the basis of value of default argument is not allowed either. You can only overload functions only on the basis of: Type of arguments. Number of arguments.
Why do you expect "bbb bbb"?
Since you are casting the instance to a
, the only information to the compiler on the first call is the version with "aaa"
, so that value is what is used.
In the second version without the cast, the compiler can see the "bbb"
, so that value is what is used.
Polymorphism impacts which method is invoked - but it doesn't impact the parameters passed. Essentially, the default values are supplied by the compiler (at the call-site), so your code is actually equivalent to:
((a)new b()).test("aaa");
new b().test("bbb");
where the "aaa"
and "bbb"
is supplied at compile time, by inspection of the resolved method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With