Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of curly braces after the "is" operator

I found in some C# source code the following line:

if(!(context.Compilation.GetTypeByMetadataName("Xunit.FactAttribute")
         is { } factAttribute))

and here is another one:

if(!(diagnostic.Location.SourceTree is { } tree))

What is the meaning of the curly braces ({ }) after the is operator?

like image 495
DasOhmoff San Avatar asked Jun 01 '20 19:06

DasOhmoff San


1 Answers

This is a new pattern matching feature which was introduced in C# 8.0 and is called property pattern. In this particular case it is used to check that object is not null, example from the linked article:

static string Display(object o) => o switch
{
    Point { X: 0, Y: 0 }         p => "origin",
    Point { X: var x, Y: var y } p => $"({x}, {y})",
    {}                           => o.ToString(),
    null                         => "null"
};
like image 69
Guru Stron Avatar answered Nov 12 '22 09:11

Guru Stron