I see the following code sometimes, and have no idea what the expression is actually testing.
public static void Something(string[] value)
{
if (value is { })
{
DoSomethingElse();
}
}
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.
s is definitelly not null. is {} is shorthand for is object and strings can be cast to object.
Feb 26, 2020 at 15:31
!, !!, ? and ?? before and after properties mean different things. When will the syntactic sugar high end?
Feb 26, 2020 at 15:59
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.
is object invalid, not is {} invalid
Feb 27, 2020 at 8:34
IActionResult is required (well technically Task<IActionResult>). If we go with your style, the if has the same result but invalid will be an object so this won't compile.