Dereference of a possible null reference (CS8602) after matching with object pattern in a switch expression

Viewed 778

I have the following code in a definition of a custom IEqualityComparer<Uri?>:

public bool Equals(Uri? x, Uri? y) => (x, y) switch
{
    (null, _) => false,
    (_, null) => false,
    ({}, {}) => x.Equals(y)
};

I'm getting a CS8602 warning on the Equals call in the last arm, telling me that there's a possibility x is null there. But I've just matched x against the object pattern {} which wouldn't match if x were null. Am I missing a possible control flow that causes x to be null in that branch or is it impossible and I should just bang-operator it away? Is it an analyzer bug or a known limitation?

Update

It might be worth noting that this only happens if I destructure the tuple. This code is correct and gives no warnings:

public bool Equals(Uri? x, Uri? y) => x switch
{
    null => false,
    {} => x.Equals(y)
};
0 Answers
Related