views:

111

answers:

2

Premise

When using code analysis (or fxCop) with C# optional parameters you can get a warning of CA1026. The short reason1 for this is not suppling all parameters with a default value.

The declaration below rightly generates this warning

public Color GetColor(bool red, bool blue = true, bool green = true)

However there is a situation where you could not supply all parameters with a default, and that is extension methods. So the declaration below generates the warning because of the first parameter:

public static bool ValidateRules(this string s, Rules rules = Rules.Default)

The compiler will not let you specify a default value on the this parameter so the only two solutions is to:

  1. Ignore the warning, which I do not like doing because it leads to bad practices.
  2. Not use extension methods, which I do not like doing because I find extension methods make the code more readible.

Questions

  • Are the above two options the only way to solve this?
  • Is fxCop/Code Analysis incorrect in it's check?

  1. The long reason
A: 

You can suppress the warning on a case-by-case basis.

Steven Sudit
+6  A: 

It's not warning you for not having defaults for all parameters - it's warning you for using optional parameters at all.

Personally I would disable this particular warning. When used with care, I think optional parameters are fine. You should think carefully about them particularly in terms of versioning of the default parameter value and in terms of languages which don't support them (including C# before v4) but in many environments the downsides really aren't an issue - and you can end up with much simpler code than by specifying overloads all over the place.

Jon Skeet