Why the default method parameters should be compile time constants in C #

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

I know this is true, but why is this so? It seems like something like this:

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

The compiler can 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 not work, or would it be, but is it just a design decision?

+6
source share
1 answer

Because the specification says so:

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

• constant expression

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

• default form expression (S), where S is the value type

As for why the language developers decided to do this, which we can only guess. However, another part of the specification prompts the answer:

When arguments are omitted from a member of the function with the corresponding optional parameters, the default arguments of the member of the function are implicitly passed. Since they are always constant, their evaluation will not affect the procedure for evaluating the remaining arguments.

+7
source

Source: https://habr.com/ru/post/976370/


All Articles