Curly Braces In C#

巧了我就是萌 提交于 2021-02-04 15:54:11

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/60103804/curly-braces-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!