4

Possible Duplicate:
method overloading vs optional parameter in C# 4.0

It seems as though most of the cons of optionals like versioning issues could be addressed by making optional parameters simply convert into overloads. Is there a technical reason the C# optional parameters are not implemented in way that reduces to overloads?

Community
  • 1
  • 1
Joshua Enfield
  • 17,642
  • 10
  • 51
  • 98
  • What's to say the overload it would reduce to doesn't already exist? – Anthony Pegram Jan 15 '12 at 00:08
  • possible duplicates: http://stackoverflow.com/questions/3316402/method-overloading-vs-optional-parameter-in-c-sharp-4-0 http://stackoverflow.com/questions/251868/should-you-declare-methods-using-overloads-or-optional-parameters-in-c-sharp-4-0 – keyboardP Jan 15 '12 at 00:10
  • 1
    It's a good point. The compiler could just throw a compile error i.e. treat the optional as expanding out into overloads, and if they exist you have to remove the optional or the method. I could very well be missing something though. – Joshua Enfield Jan 15 '12 at 00:13
  • 1
    I fail 100% to see how this is an exact duplicate question. The questions are not [directly] related at all. Did moderators even look at the linked dupes? – Joshua Enfield Jan 16 '12 at 14:43

1 Answers1

2

One reason is that if the compiler automatically compiled down optional parameters into the overloads, it would conflict with the developers ability to define them on their own. For example the following code is legal.

class Container {

  public void Example(int x) {
    ...
  }

  public void Example(int x, int y = 42) {
    ...
  }
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • Or `public void Example(int x, int y = 42, int z = 43)`, where calling `Example(10, z:44)` will be equivalent to `Example(10, 42, 44)`? With just the two parameters, will `y` ever be set to its default value? – Matthew Strawbridge Jan 15 '12 at 01:09
  • 3
    It seems there are perfectly valid reasons for that code to be illegal, perhaps more so than the reasons for it to be legal! It's far from immediately obvious what happens if I call `Container.Example(x)`. Of course, I realize this was a design decision made long ago, that there's no "right" answer, and it's never going to be changed, so the question is rather pointless. – Cody Gray - on strike Jan 15 '12 at 09:03