My code currently looks like this:
if (control != null && control.Meta != null && control.State != null)
{
ConfigureMeta(control, control.Meta);
ConfigureColors(control, control.State);
}
Is there now another cleaner way that I could do this null check using the "?" that was added to the latest version of C#?
It is a good idea to check for null explicitly because: You can catch the error earlier. You can provide a more descriptive error message.
Typically, you'll check for null using the triple equality operator ( === or !== ), also known as the strict equality operator, to be sure that the value in question is definitely not null: object !== null . That code checks that the variable object does not have the value null .
You can check for null with the typeof() operator in JavaScript. Curiously, if you check with typeof() , a null variable will return object .
You can use the null-conditional operator (C#6) to reduce one check - added (July 2015)
null-conditional operators
Tests the value of the left-hand operand for null before performing a member access (
?.
) or index (?[]
) operation; returnsnull
if the left-hand operand evaluates to null.
if (control?.Meta != null && control?.State != null)
{
}
if you really really really want to make multiple checks easier and you have printable character OCD (and you just like writing methods for the fun of it)
You could use the following
public bool CheckAll(params object[] refs) => refs.All(x => x != null);
...
if (CheckAll(control?.Meta, control?.State))
{
}
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