org.sonar.plugins.csharp.S3451.html Maven / Gradle / Ivy
Why is this an issue?
DefaultValue does not make the compiler set
the default value, as its name may suggest. What you probably wanted to use is DefaultParameterValue.
The DefaultValue attribute from the
System.ComponentModel
namespace, is sometimes used to declare a member’s default value. This can be used, for instance, by the reset
feature of a visual designer or by a code generator.
public void DoStuff([DefaultValue(4)] int i)
{
// i is not automatically assigned 4
}
The Optional attribute from the
System.Runtime.InteropServices
namespace is sometimes used to indicate that a parameter is optional, as an alternative to the
language-specific construct.
public void DoStuff([Optional] int i)
{
// i would be assigned default(int) = 0
}
The use of [DefaultValue]
with [Optional]
has no more effect than [Optional]
alone. That’s because
[DefaultValue]
doesn’t actually do anything; it merely indicates the intent for the value.
class MyClass
{
public void DoStuff([Optional][DefaultValue(4)] int i, int j = 5) // Noncompliant
{
Console.WriteLine(i);
}
public static void Main()
{
new MyClass().DoStuff(); // prints 0, since [DefaultValue] doesn't actually set the default, and default(int) is used instead
}
}
More than likely, [DefaultValue]
was used in confusion instead of [DefaultParameterValue]
, the language-agnostic version
of the default parameter initialization mechanism provided by C#.
class MyClass
{
public void DoStuff([Optional][DefaultParameterValue(4)] int i, int j = 5)
{
Console.WriteLine(i);
}
public static void Main()
{
new MyClass().DoStuff(); // prints 4
}
}
Notice that you can’t use both [DefaultParameterValue]
and default parameter initialization on the same parameter.
void DoStuff([Optional][DefaultParameterValue(4)] int i = 5) // Error CS1745 Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute
Resources
Documentation
- OptionalAttribute Class
- DefaultValueAttribute Class
- DefaultParameterValueAttribute
Class
- Optional arguments (C# Programming Guide)
Articles & blog posts