mantal
mantal

Reputation: 1209

Is this pattern matching expression equivalent to not null

I stumbled upon this code on github:

if (requestHeaders is {})

and I don't understand what it does exactly.

Upon experimenting it's seems to only be false when requestHeaders is null.

Is this just another way of writing if (requestHeaders != null) or if (!(requestHeaders is null))?

Upvotes: 23

Views: 7153

Answers (3)

Patrick McDonald
Patrick McDonald

Reputation: 65421

One difference between != null and is { } is that the first can be overridden whereas the second cannot.

For example, if you paste the following into a new Console app and run it

DoNotDoThis? a = new(); // a isn't null

Console.WriteLine("a == null: {0}", a == null);
Console.WriteLine("a != null: {0}", a != null);
Console.WriteLine();
Console.WriteLine("a is null: {0}", a is null);
Console.WriteLine("a is not null: {0}", a is not null);

public class DoNotDoThis
{
    public static bool operator ==(DoNotDoThis? a, DoNotDoThis? b)
    {
        return ReferenceEquals(b, null);
    }

    public static bool operator !=(DoNotDoThis? a, DoNotDoThis? b)
    {
        return !(a == b);
    }
}

you get the following output

a == null: True
a != null: False

a is null: False
a is not null: True

Interestingly, ReSharper gives you a warning on the first line:

Expression is always false

Upvotes: 1

JCH2k
JCH2k

Reputation: 3621

As an addition to @vendettamit's answer:

Since C# 9, it is the same as writing

if (requestHeaders is not null)

which does not require any further explanation

Upvotes: 6

vendettamit
vendettamit

Reputation: 14677

The pattern-matching in C# supports property pattern matching. e.g.

if (requestHeaders  is HttpRequestHeader {X is 3, Y is var y})

The semantics of a property pattern is that it first tests if the input is non-null. so it allows you to write:

if (requestHeaders is {}) // will check if object is not null

You can write the same type checking in any of the following manner that will provide a Not Null Check included:

if (s is object o) ... // o is of type object
if (s is string x) ... // x is of type string
if (s is {} x) ... // x is of type string
if (s is {}) ...

Read more here.

Upvotes: 19

Related Questions