S3240 and S3358 conflicts

Having the following code:

enum TestEnum
{
    Value1,
    Value2
}

private static TestEnum DeserializeConfiguration(string configuration)
{
    TestEnum result;
    
    if (configuration == "OldValue")
    {
        result = TestEnum.Value1;
    }
    else
    {
        result = Enum.TryParse(configuration, true, out TestEnum databaseType)
            ? databaseType
            : TestEnum.Value1;
    }

    return result;
}

SonarQube raises S3240 “The simplest possible condition syntax should be used” on the IF statement.

Following the rule I can rewrite the code to the following method:

private static TestEnum DeserializeConfiguration(string configuration)
{
    TestEnum result;

    result = configuration == "OldValue"
        ? TestEnum.Value1
        : Enum.TryParse(configuration, true, out TestEnum databaseType)
            ? databaseType
            : TestEnum.Value1;

    return result;
}

But, this raises S3358 “Ternary operators should not be nested”.

At least for readability S3240 should not raise if a ternary operator is already part of the IF/ELSE statement.

1 Like

I agree that this should be reported a such. Note that is can be written way cleaner with pattern matching:

private static TestEnum DeserializeConfiguration(string configuration) => configuration switch
{
	"OldValue" => TestEnum.Value1,
	_ when Enum.TryParse(configuration, true, out TestEnum databaseType) => databaseType,
	_ => TestEnum.Value1,
};

The original code is a bit more complex so that you pattern-matching-hint does not apply.
But, I’m fine if you agree that S3240 should be adopted to not conflict with S3358.

Hello @lg2de,

This false positive have already been reported here: S3240 false-positive for interpolated string with condtional operator.

I will update the priority of the ticket to ensure it is included in our next hardening sprint.

Have a nice day!