org.sonar.plugins.csharp.S3466.html Maven / Gradle / Ivy
Why is this an issue?
When optional parameter values are not passed to base method calls, the value passed in by the caller is ignored. This can cause the function to
behave differently than expected, leading to errors and making the code difficult to debug.
How to fix it
Code examples
Noncompliant code example
public class BaseClass
{
public virtual void MyMethod(int i = 1)
{
Console.WriteLine(i);
}
}
public class DerivedClass : BaseClass
{
public override void MyMethod(int i = 1)
{
// ...
base.MyMethod(); // Noncompliant: caller's value is ignored
}
static int Main(string[] args)
{
DerivedClass dc = new DerivedClass();
dc.MyMethod(12); // prints 1
}
}
Compliant solution
public class BaseClass
{
public virtual void MyMethod(int i = 1)
{
Console.WriteLine(i);
}
}
public class DerivedClass : BaseClass
{
public override void MyMethod(int i = 1)
{
// ...
base.MyMethod(i);
}
static int Main(string[] args)
{
DerivedClass dc = new DerivedClass();
dc.MyMethod(12); // prints 12
}
}
Resources
Documentation
Microsoft Learn - Optional
Arguments
© 2015 - 2024 Weber Informatics LLC | Privacy Policy