All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S1006.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

Default arguments are determined by the static type of the object.

class Base
{
    public virtual void Run(int distance = 42) { /* ... */ }
}

class Derived : Base
{
    public override void Run(int distance = 5) { /* ... */ }
}

Base x = new Base();
x.Run(); // Here the default value of distance is 42
Derived d = new Derived();
d.Run(); // Here the default value of distance is 5
Base b = new Derived();
b.Run(); // Here the default value of distance is 42, not 5

If a default argument is different for a parameter in an overriding method, the value used in the call will be different when calls are made via the base or derived object, which may be contrary to developer expectations.

Default parameter values in explicit interface implementations will be never used, because the static type of the object will always be the implemented interface. Thus, specifying default values in this case is confusing.

interface IRunner
{
    void Run(int distance = 42) { /* ... */ }
}

class Runner : IRunner
{
    void IRunner.Run(int distance = 5) { /* ... */ }
}

IRunner x = new Runner();
x.Run(); // Here the default value of distance is 42
Runner d = new Runner();
d.Run(); // This will not compile as the Run method is only visible through the specified interface

Noncompliant code example

using System;

public class Base
{
    public virtual void Write(int i = 42)
    {
        Console.WriteLine(i);
    }
}

public class Derived : Base
{
    public override void Write(int i = 5) // Noncompliant
    {
        Console.WriteLine(i);
    }
}

public class Program
{
    public static void Main()
    {
        var derived = new Derived();
        derived.Write(); // writes 5
        Print(derived); // writes 42; was that expected?
    }

    private static void Print(Base item)
    {
        item.Write();
    }
}

Compliant solution

using System;

public class Base
{
    public virtual void Write(int i = 42)
    {
        Console.WriteLine(i);
    }
}

public class Derived : Base
{
    public override void Write(int i = 42)
    {
        Console.WriteLine(i);
    }
}

public class Program
{
    public static void Main()
    {
        var derived = new Derived();
        derived.Write(); // writes 42
        Print(derived);  // writes 42
    }

    private static void Print(Base item)
    {
        item.Write();
    }
}

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy