Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curly Braces In C#

Tags:

syntax

c#

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.

like image 274
Tee Avatar asked Feb 06 '20 21:02

Tee


Video Answer


1 Answers

{} 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

like image 121
Robert J Avatar answered Oct 13 '22 15:10

Robert J