Recently, I wanted to add an optional parameter to an extension method. The original method looked like this:
public static class Extensions {
public static bool Foo(this IFoo target) {
target.DoIt(true);
}
}
This is obviously a simplified version but let's go from that.
What I did is:
public static class Extensions {
public static bool Foo(this IFoo target, bool flag = true) {
target.DoIt(flag);
}
}
All I did is introduce an optional parameter with a default value, right? What I was expecting was the compiler to generate the overloaded method, without the flag. This partially happened. Any code that I recompiled was able to compile and execute without any problems, even without the parameter like this:
...
IFoo foo = new FooBar();
foo.Foo();
...
However, any code that was built against the previous version of Foo() did not work, throwing the following exception:
Unhandled Exception: System.MissingMethodException: Method not found: 'Boolean Models.Class1.Foo()'.
at DefaultParamsTests.Program.Main(String[] args)
This is obviously a problem for us as we do have a public API that our customers do leverage and this would be a breaking change.
The solution is to explicitly create an overload:
public static class Extensions {
public static bool Foo(this IFoo target) {
target.DoIt(true);
}
public static bool Foo(this IFoo target, bool ) {
target.DoIt(true);
}
}
However, Resharper does suggest that I could introduce an optional parameter for method foo.
If I do follow the refactoring it basically does what I showed above. However, that won't work for existing code.
I have looked at the generated IL using both Reflector and dotPeek. Neither is showing the generation of the overload.
What am I missing?