Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding default parameters in C# [duplicate]

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);
    }
}
like image 502
maxp Avatar asked Dec 17 '13 12:12

maxp


People also ask

How are parameters passed by default in C?

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.

What is default parameter in C?

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.

Does C support default parameter?

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.

Can we pass default arguments to overloaded functions?

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.


1 Answers

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.

like image 128
Marc Gravell Avatar answered Sep 20 '22 11:09

Marc Gravell