Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest way to check for null and assign another value if not

I am pulling varchar values out of a DB and want to set the string I am assigning them to as "" if they are null. I'm currently doing it like this:

if (string.IsNullOrEmpty(planRec.approved_by) == true)   this.approved_by = ""; else   this.approved_by = planRec.approved_by.toString(); 

There seems like there should be a way to do this in a single line something like:

this.approved_by = "" || planRec.approved_by.toString(); 

However I can't find an optimal way to do this. Is there a better way or is what I have the best way to do it?

like image 779
Splashlin Avatar asked Jul 13 '09 16:07

Splashlin


People also ask

Does .ANY check for null?

Any() internally attempts to access the underlying sequence ( IEnumerable ). Since the object can be null, there is no way to access the enumerable to validate it, hence a NullReferenceException is thrown to indicate this behavior.

Is null shortcut C#?

The null-coalescing operator ( ?? ) is like a shorthand, inline if/else statement that handles null values. This operator evaluates a reference value and, when found non-null, returns that value. When that reference is null , then the operator returns another, default value instead.

What is a null check?

A null indicates that a variable doesn't point to any object and holds no value. You can use a basic 'if' statement to check a null in a piece of code. Null is commonly used to denote or verify the non-existence of something.


1 Answers

Try this:

this.approved_by = IsNullOrEmpty(planRec.approved_by) ? "" : planRec.approved_by.toString(); 

You can also use the null-coalescing operator as other have said - since no one has given an example that works with your code here is one:

this.approved_by = planRec.approved_by ?? planRec.approved_by.toString(); 

But this example only works since a possible value for this.approved_by is the same as one of the potential values that you wish to set it to. For all other cases you will need to use the conditional operator as I showed in my first example.

like image 95
Andrew Hare Avatar answered Oct 18 '22 05:10

Andrew Hare