Skip to content

Fix S1144 FP: Erroneously flagged Add() method used in Collection Initializer #9778

@markusschaber

Description

@markusschaber

Description

When a custom Add(...) Method is only used in a collection initializer, SonarQube regards it as unused, although it's called in the initialization code.

Reproducer

using Xunit;

public class Class1
{
    private static readonly SettingsDict TheoryData = new()
    {
        new MySettings(1, 2), new MySettings(3, 4)
    };

    // Theory data in xUnit is restricted to serializable values, so we need to
    // pack our data into a dictionary, and use the keys as theory data.
    public static readonly TheoryData<string> Settings = new(TheoryData.Keys);

    [Theory]
    [MemberData(nameof(Settings))]
    public void SomeTest(string key)
    {
        var (alpha, beta) = TheoryData[key];
        // some fake test
        Assert.NotEqual(alpha, beta);
    }

    private class SettingsDict : Dictionary<string, MySettings >
    {
        // This "Add" method triggers csharpsquid:S1144
        // Remove the unused private method Add.
        internal void Add(MySettings settings)
        {
            Add($"{settings.Alpha}/{settings.Beta}", settings);
        }
    }

    // Some arbitrary data type which we (have to) use as (part of) our theory data.
    private record MySettings(int Alpha, int Beta);
}

Product and Version

SonarQube for IDE 11.6.0.83783 (in JetBrains Rider)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions