3

In the last couple of weeks I started encountering this new syntax in C#:

if (someObj is { })  
{    
    do some stuff 
}

so it returns bool. It seems like JavaScript a little bit. But what exactly does this check do? Is it identical to this?

if (someObj == null)
{
    do some stuff
}

I know that new versions of C# contain a lot of syntactic sugar. Is this part of that? Does it have some name or something? E.g., I know that ?: is called the ternary operator and ?. is called the Elvis operator. But what is is { }? Is it even an operator?

And yes, I've tried to search online before asking here, but it seems that Google refuses to find anything useful concerning the is { } syntax, because of the braces in the request.

Boann
  • 48,794
  • 16
  • 117
  • 146
Serenkiy
  • 249
  • 3
  • 14
  • 4
    Does this answer your question? [C# - meaning of curly braces after the "is" operator](https://stackoverflow.com/questions/62139886/c-sharp-meaning-of-curly-braces-after-the-is-operator) This is a [property pattern](https://devblogs.microsoft.com/dotnet/do-more-with-patterns-in-c-8-0) – Pavel Anikhouski Jun 05 '20 at 10:03
  • Yes, it's really helpful. Now, I know that it's called property pattern, so I can google it further, thanks. – Serenkiy Jun 05 '20 at 10:18

1 Answers1

4

In the more general sense, this is member-based pattern matching - for example:

if (foo is { Id: 42, Name: "abc"})
{

}

tests whether foo has Id 42 and Name "abc". In this case, you are testing zero properties, so it effectively becomes the same as is object (i.e. a not null test, or a no-op true for non-nullable value-types).

To compare against what you have in the question (if (someObj == null)) - it is the opposite of that, noting that it will also not use an overloaded == operator for the null test (which == null will).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900