CA1026 (all parameters should have default values) and extension methods
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.
You can suppress the warning on a case-by-case basis.
An argument that I am missing in Jon Skeet's answer is also about maintainability: Default values are always filled in with it's value in the IL (intermediate language). This is an issue if you're using external libraries.
Here are steps to reproduce a simple example:
- Create a console app
- Add a
ClassLibrary
project to it - Add the following code:
Program.cs
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var obj = new Class1();
Console.WriteLine(obj.Foo());
Console.ReadKey();
}
}
}
and in your Class1.cs
namespace ClassLibrary1
{
public class Class1
{
public string Foo(string str = "http")
{
return str;
}
}
}
If you run it you will see 'http', as expected.
- Now change "http" to "https"
- Compile only the library (maybe even unload the console project)
- Copy the dll from the library's bin folder to the console app's bin folder by hand
- Run the console app from the command line, not from within VS!
You will still see http
! With ILSpy you can see that http
is hardcoded in the console app.
In this case this could lead to a security issue if the developer thinks he is safe by replacing the "http" to "https" in the default value.
So if external libraries are updated always compile your code again. Or just don't use default values.
Just create a separate method:
public string Foo()
{
return Foo("https");
}
public string Foo(string str)
{
return str;
}