Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a cleaner way to handle null checking now that the ? test exists for a variable?

Tags:

c#

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

like image 672
Alan2 Avatar asked Feb 26 '19 05:02

Alan2


People also ask

Why is checking for null a good practice?

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.

How do you make sure an object is not null?

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 .

How to check whether a value is null or not in JavaScript?

You can check for null with the typeof() operator in JavaScript. Curiously, if you check with typeof() , a null variable will return object .


1 Answers

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; returns null 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))
{
}
like image 67
TheGeneral Avatar answered Oct 02 '22 21:10

TheGeneral