Overriding ToString() for record type can lead to incorrect Code Smell

When you create a record type in C# with an overriden ToString() method and then override this type, you may need to provide a new implementation of ToString() that does nothing besides calling base.ToString(). This may be necessary because omitting a custom ToString() method for a record type signals the compiler to create one for you. Because of this, for overriding record types, the default is not base.ToString().

When you do this however, Sonar will yield a code smell “Overriding members should do more than simply call the same member in the base class”

Example:

public record A {
    public override string ToString() {
        return "haha, pretty cool!";
    }
}

public record B : A {
     public override string ToString() {
        return base.ToString();
    }
}

public record C: A {
}


// Checking the following:
var b = new B();
var c = new C();
var equal = b.ToString() == c.ToString(); // Equal will be false

When you run the above through Sonar however, it’ll give you a code smell warning that type B should not override ToString() just to call base.ToString().

I hope this makes sense.

Hi @Robert_Mulder,

Thanks for reporting this false positive. We created an issue to track work on this, and a PR to fix it is in the works:
Issue: S1185: Derived records need to override ToString to prevent default code generation by the compiler · Issue #5686 · SonarSource/sonar-dotnet · GitHub
PR: S1185: Derived records need to override ToString to prevent default code generation by the compiler by martin-strecker-sonarsource · Pull Request #5687 · SonarSource/sonar-dotnet · GitHub

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.