[C#] S3604 causes false-positive when using Primary Constructor from C# 12

EDIT: Just noticed that you are already aware of this (mentioned in the blog post) and that there is also already an existing topic for this. Feel free to close.

This issue occurs in SonarLint for Visual Studio (v7.4.0.80741).

In C# 12, they introduced a new way of writing constructors. Instead of

internal class Mapping
{
  public string Name { get; }
  public List<MappingRange> Ranges { get; } = [];

  public Mapping(string name)
  {
    Name = name;
  }
}

we can instead use a “Primary Constructor” by writing the parameters directly after the class definition and then assigning them to the properties:

internal class Mapping(string name)
{
  public string Name { get; } = name;
  public List<MappingRange> Ranges { get; } = [];
}

However, this will cause false-positives by rule S3604 on both = name; and = [];.

It says to the member initializers should be removed because all constructors supposedly already set a value for the members. But removing the assignments will cause the compiler to flag the constructor parameter string name as being unused (with error code CS9113: Parameter is unread).

Thanks for following up :slight_smile:

1 Like