SonarLint: Why does this condition always evaluates to true?

78 views Asked by At

I'm writing a generic extension function which parses a string value to other types. The function basically looks like this:

public static T Parse<T>(string input)
{
    T result = (T)(typeof(T) switch
    {
        Type t when t == typeof(DateOnly) => DateOnly.Parse(input, CultureInfo.InvariantCulture),
        _ => Convert.ChangeType(input, typeof(T))
    });

    return result;
}

Note that this is simply a snippet which demonstrates the issue.

I got the case guard from this post (since I haven't used those before) and changed it to a switch expression:

Switch case and generics checking

However the line with the case guard produces the warning S2589: Change this condition so that it does not always evaluate to 'True'. Note that I'm using Sonar Lint for C# linting. The warning generates a green squiggly line under Type t:

squiggly line

The function seems to work as intented even if I add more types to be parsed differently.

So my question is: Is this an issue with Sonar Lint or am I missing something with case guards?

0

There are 0 answers