Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reasoning for C# not supporting optional/default arguments?

I long for those sweet optional arguments from the days when I programmed in C++ more. I know they don't exist in C#, but my question is Why.

I think method overloading is a poor substitute which makes things messy very quickly.

void foo(int x,int y,int z=0){
  //do stuff...
}

//is so much more clean than

void foo(int x,int y){
  foo(x,y,0);
}
void foo(int x,int y,int z){
 //do stuff
}

I just do not understand what the reasoning is. The C# compiler would obviously not have a problem supporting this just Microsoft elected not to support it.

Why, when C# was designed, did they not want to support optional arguments?

like image 772
Earlz Avatar asked Mar 02 '10 17:03

Earlz


4 Answers

As Andrey says, C# 4 has optional parameters and named arguments. However, it's worth pointing out that one of the concerns which made Anders reluctant to include them to start with - namely that the default value (which has to be a constant) gets baked into the calling code - is still present. In other words, it's the same problem as publicly accessible const values from C# 1.

like image 166
Jon Skeet Avatar answered Nov 05 '22 08:11

Jon Skeet


Its not there yet, but it is in C# 4. This is largely to do with cost, and how well the feature fits in with the major new parts of the language (such as Generics in .Net 2, or linq in 3). Optional arguments fit will with the new dynamic stuff coming in version 4, so have been included.

To quote Eric Lippert (Who was himself quoting Eric Gunnerson) on why many seemingly good features are not included:

(1) this is not a subtractive process; we don't start with C++ or Java or Haskell and then decide whether to leave some feature of them out. And (2) just being a good feature is not enough. Features have to be so compelling that they are worth the enormous dollar costs of designing, implementing, testing, documenting and shipping the feature. They have to be worth the cost of complicating the language and making it more difficult to design other features in the future.

like image 27
Jack Ryan Avatar answered Nov 05 '22 08:11

Jack Ryan


i think it is useless to try to answer question "Why?". But i have good news, C# 4.0 has them.

like image 45
Andrey Avatar answered Nov 05 '22 10:11

Andrey


Optional arguments are not that simple as they look like. You might get complex problems if you have overloaded methods which all have optional arguments. The resolution rules can become very complicated very quickly. I guess for the first version of C# there was not good solution, so they skipped the optional parameters.

But you probably know that C# 4.0 will have optional and named arguments, so it seems not to be a bad idea in general! ;-)

like image 1
Achim Avatar answered Nov 05 '22 10:11

Achim