Giles
Giles

Reputation: 1424

Optional parameters and method overloading

I've come across a library method with three parameters, all with default values:

virtual M(bool b1 = false, string s1 = null, bool b2 = true)

Method M shouldn't have parameter s1, so I want to remove it, but I don't want to make a breaking change in the DLL. Clients can obviously ignore s1, but I don't want to leave it there because M can be overridden and parameter s1 is misleading. So here was my attempt:

virtual M(bool b1 = false, bool b2 = true)
[Obsolete] virtual M(bool b1, string s1, bool b2 = true)

I figured that since optional parameters are compiled into the call site, existing clients would carry on calling the method with three parameters, whereas new or recompiled clients not using s1 would link to the method with two parameters.

Each call to M resolves okay, except this one:

M(b2: false);

The compiler reports that the call is ambiguous between "M(bool, bool)" and "M(bool, string, bool)".

Oddly, in the parameter info (Ctrl+Shift+Space), Visual Studio is still showing the default values on the method with three parameters (despite cleaning and rebuilding, restarting VS, unloading and reloading projects).

Obviously I can fix this by calling the new M something different, but I'm curious as to why it's not linking. Should it (and something's just out of step, as the out-of-date parameter info suggests), or does the compiler have a genuine issue with this?

EDIT

Like @p.s.w.g and as per @JonSkeet's suggestion, I can't reproduce this in fresh code, so I guess the question becomes: is there anything else I can try other than rebuilding, restarting, reloading to force VS to relink this?

Upvotes: 3

Views: 328

Answers (1)

Giles
Giles

Reputation: 1424

Well this is embarrassing and interesting in equal measures (okay - maybe slightly more embarrassing than interesting).

The compiler was correct (as it almost always is!). I had assumed that the compiler error was referring to the two M methods I outlined in the question, but the client code with the error was also overriding the original M with three parameters, and still providing the defaults to all three parameters.

I only discovered "the third M" when I actually added the [Obsolete] (sorry - I'd only posted it for illustration - didn't think that would be relevant) and got a warning about overriding an obsolete method.

I think this probably supports @p.s.w.g's comment!

Upvotes: 1

Related Questions