16

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?

LarsTech
  • 80,625
  • 14
  • 153
  • 225
DasOhmoff San
  • 865
  • 6
  • 19

1 Answers1

21

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"
};
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • Is it works the same as using `not null` pattern? I know the empty braces allow us to create an alias for this pattern but I'm not sure in the case if we don't need the alias. – anuith Aug 09 '22 at 04:09
  • 1
    @anuith yes, it does. If you don't need alias you should be able to use both interchangeably. – Guru Stron Aug 09 '22 at 20:02
  • @anuith The curly bracket pattern is required when you want to assign the checked value directly to a newly declared variable such as in `if (iterator.Read() is {} item)`. – d.k. Jun 20 '23 at 09:22