What does "is { }" mean?

While Daniel's answer is right, I think it might be useful to add some context about why you may see the empty property pattern in use. Consider this example controller method that needs some validation done:

public async Task<IActionResult> Update(string id, ...) 
{
    if (ValidateId(id) is { } invalid)
        return invalid;
    ...
}

In the above, ValidateId() could return null or an instance of BadObjectRequestResult. If the former is returned, the validation is successful and moves on to the rest of the body of Update. If the latter is returned, is {} is true (i.e. of course an instance of BadObjectRequestResult is an object), and the validation fails.

Nicely, out of this we've also provided a variable name, invalid, which we can return immediately. Without that we'd need slightly more verbose code.

public async Task<IActionResult> Update(string id, ...) 
{
    var invalid = ValidateId(id);
    if (invalid != null)
        return invalid;
    ...
}

Whether one is more readable or the other is up to the reader, I've just presented one way the empty property pattern can be used.


That's just the empty property pattern in C# 8, meaning the value not null. It matches any value type or reference type. As Panagiotis Kanavos notes in the comments, this is equivalent to the good old value is object check which has been in C# for a long time.

Generally if you were to specify a property, then it would match or not. This esoteric example illustrates that:

if (value is { Length: 2 })
{
   // matches any object that isn't `null` and has a property set to a length of 2
}

The property patterns work best and are most clear when comparing with other patterns in cases such as switch expressions.

Tags:

C#

C# 8.0