Skip to content

NET-3554 Fix S3240 FP: "Use the '??' operator here" when implicit conversions are applied #9793

Open

Description

@sbont

Description

The the case that an implicit operator should be applied for both the left-hand expression and the null case expression, the ?? operator is not applicable, bcause implicit conversions are not applied. The only way to get this to work is to use a null check in a ternary operator. However, Sonar flags these with S3240. See example.

Reproducer

public class Result<T>
{
    public string? Error { get; init; }
    public T Value { get; init; }

    public static implicit operator Result<T>(string error) => new Result<T> { Error = error };
    public static implicit operator Result<T>(T value) => new Result<T> { Value = value };

    public static Result<T> Example(T? value)
    {
        // error: Operator '??' cannot be applied to operands of type 'T?' and 'string'
        return value ?? "Value is null";
        // works: implicit conversions are applied. However, Sonar complains with "Use the '??' operator here"
        return value == null ? "Value is null" : value;
    }
}

Product and Version

SonarQube Cloud

Activity

  1. self-assigned this
    on Apr 7, 2026
  2. changed the title [-]Fix S3240 FP: "Use the '??' operator here" when implicit conversions are applied[/-] [+]NET-3554 Fix S3240 FP: "Use the '??' operator here" when implicit conversions are applied[/+] on Apr 7, 2026
  3. github-actions commented on Apr 7, 2026

    @github-actions
    Contributor

    Internal ticket NET-3554

  4. mary-georgiou commented on Apr 7, 2026

    @mary-georgiou
    Contributor

    Hello @sbont I confirm this is a false positive.
    Thanks for the report!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

False PositiveRule IS triggered when it shouldn't be.

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions