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.
{} 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With