9

I was playing around with some code and I was wondering if any can tell me what the curly braces in this code represents. I thought it would've been for an empty object but that doesn't seem to be the case.

 Person person = new Person{};

            if (person is {}){
                Console.WriteLine("Person is empty.");
            } else {
                Console.WriteLine("Person is not empty.");
            }

It compiles just fine; but if I populate the properties of the person class it still falls into the person is empty part of the if statement.

Tee
  • 133
  • 5

1 Answers1

10

{} means in this context a pattern matching of any type to check if the instance is not null:

if(person != null){     //the same as: if(person is {})...

}

It is like a var keyword for pattern matching, so you do not need to specify/repeat the type explicitly (although you know it).

if(GetPersonFromDb() is {} person){     //the same as: var person = GetPersonFromDb(); if(person != null)...

}

More info (see the section Special match expressions): https://hackernoon.com/whats-pattern-matching-in-c-80-6l7h3ygm

Robert J
  • 704
  • 10
  • 8
  • 4
    Thanks. Still think `GetPersonFromDb() is var person` would have been much clearer to majority of C# devs, and we wouldn't be searching for "what it means". :) I miss the old C# team who were very very hard to sell on introducing "new" stuff like this. – vulcan raven Nov 16 '20 at 20:48