Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
630 views
in Technique[技术] by (71.8m points)

C# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 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"
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...