Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must default method parameters be compile-time constants in C# [closed]

EDIT 1: I know there are alternatives such as telescoping, this was a purely educational question.

I know that this is true, but why must it be? It seems like with something like this:

public class Foo{

    private int bar;

    public void SetBar(int baz = ThatOtherClass.GetBaz(3)){
        this.bar = baz;
    }

}

The compiler could change the method to something like this:

public void SetBar(int baz){

//if baz wasn't passed:
baz = ThatOtherClass.GetBaz(3);

this.bar = baz;

}

Why wouldn't that work, or would it, and it's just a design decision?

like image 858
AlphaModder Avatar asked Oct 07 '14 18:10

AlphaModder


1 Answers

Because the spec says so:

A fixed-parameter with a default-argument is known as an optional parameter, whereas a fixed-parameter without a default-argument is a required parameter. A required parameter may not appear after an optional parameter in a formal-parameter-list. A ref or out parameter cannot have a default-argument. The expression in a default-argument must be one of the following:

• a constant-expression

• an expression of the form new S() where S is a value type

• an expression of the form default(S) where S is a value type

As to why the language designers chose to do this, that we can only guess at. However, another piece of the spec hints at an answer:

When arguments are omitted from a function member with corresponding optional parameters, the default arguments of the function member declaration are implicitly passed. Because these are always constant, their evaluation will not impact the evaluation order of the remaining arguments.

like image 89
BradleyDotNET Avatar answered Oct 02 '22 21:10

BradleyDotNET