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?
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.
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.
i think it is useless to try to answer question "Why?". But i have good news, C# 4.0 has them.
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! ;-)
精彩评论