Posts Tagged ‘C#4’

The possible problem with optional parameters in .Net 4.0

May 2nd, 2012 No comments

Few things regarding code analysis
While running code analysis with all rules turned on i’ve hit awarning on the following line:

Public abstract void Foo(IEnumerable<T> values, bool state= true);

CA1026 : Microsoft.Design : Replace method ‘Foo(IEnumerable, bool)’ with an overload that supplies all default arguments.
MSDN link –
This was very confusing. Is Microsoft suggesting to stop using the cool C#4 feature of optional parameters (bool state= true)?

After digging around we understand why. There’s an implication on using optional parameters. They are compiled as constants at the calling side.
So if you use optional parameters on public API and later want to change the default, that won’t work for clients who already use your API without recompiling.

Bottom line:
Be careful when you use optional parameters. Better not use them on public API.

Thanks to Ron who bring this example.

Categories: .Net, C# Tags: