False S4144 when otherwise-identical generic methods have different type constraints

  • Operating system: Windows 11
  • SonarLint plugin version: 6.14.1.66430
  • Visual Studio version: 2022 (Version 17.6.0 Preview 2.0)
  • Programming language you’re coding in: C#
  • Is connected mode used: No

Description: Given two methods with identical code and a single type parameter T; and, given different type constraints, a false S4144 (“Update this method so that its implementation is not identical to …”) message is generated. The code below demonstrates the problem. In Visual studio hovering over TestReferenceType() will show the S4144.

While it is true that the body syntax of TestValueType() and TestReferenceType() are the identical, due to differences between C# value and reference types, the semantics are different. Attempting to use a single function with constraint T : notnull fails compilation due to these differences.

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace S4144Demo;

public abstract class Wrap<T> where T : notnull { }

public class WrapV<T> : Wrap<T> where T : notnull {
    public T Value { get; init; }
    internal WrapV(T value) => Value = value;
}

public class WrapN<T> : Wrap<T> where T : notnull {
    private WrapN() { }
    internal static WrapN<T> Singleton = new();
}

public static class Wrap {
    public static Wrap<T> From<T>(T? value) where T : struct =>
        value is T v ? new WrapV<T>(v) : WrapN<T>.Singleton;
    public static Wrap<T> From<T>(T? value) where T : class =>
        value is not null ? new WrapV<T>(value) : WrapN<T>.Singleton;
}

public static class S4144 {
    public static void TestValueType<T>(T? value) where T : struct {
        var maybe = Wrap.From(value);
        Assert.AreEqual(value, (maybe as WrapV<T>)!.Value);
    }
    public static void TestReferenceType<T>(T? value) where T : class {
        var maybe = Wrap.From(value);
        Assert.AreEqual(value, (maybe as WrapV<T>)!.Value);
    }
}
1 Like

Hi @sainsworth, thanks for the feedback! Much appreciated.

I confirm the false positive and I added an issue on our side. You can follow the progress here: S4144: FP when type constraints are used · Issue #7068 · SonarSource/sonar-dotnet · GitHub

1 Like