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();
}
}
Is is what is known as a state of being verb. State of being verbs do not express any specific activity or action but instead describe existence. The most common state of being verb is to be, along with its conjugations (is, am, are, was, were, being, been). As we can see, is is a conjugation of the verb be.
Summary of Key Points. "Happy" is the most common definition for :) on Snapchat, WhatsApp, Facebook, Twitter, Instagram, and TikTok. :) Definition: Happy.
Tis is defined as a shortened version of saying it is. An example of tis is the line in the song "Deck the Halls" about it being the season to be jolly. contraction.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With