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

12

145

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?

Abstemious answered 13/7, 2009 at 16:28 Comment(1)
The == true is superfluous here...Upsilon
T
154

Try this:

this.approved_by = IsNullOrEmpty(planRec.approved_by) ? string.Empty : 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.

Thorlay answered 13/7, 2009 at 16:29 Comment(3)
Doesn't this null coalescing operator throw a nullreference anyways? The way I see this code does the following: if (planRec.approved_by == null) { this.approved_by = planRec.approved_by.toString(); //<= nullref } else { this.approved_by = planRec.approved_by;}. If I'm wrong please point out the error.Twentieth
@Twentieth is right, the code is broken. Here's a fix using another fun operator: this.approved_by = planRec.approved_by?.toString() ?? ""; <- That's the null-conditional operator, and I don't think it was around when this question was first asked and answered. Hopefully OP sees this, so he can go refactor his 7 year old code, from two jobs ago :) .Siffre
I could swear I've seen some kind of syntax that lets you assign to an attribute of an object if that object isn't null, like someObject?.someAttribute = value; but I can't seem to find anything like that.Herb
Z
87

Starting with C# 8.0, you can use the ??= operator to replace the code of the form

if (variable is null)
{
    variable = expression;
}

with the following code:

variable ??= expression;

More information is here

Zoosporangium answered 7/10, 2019 at 12:55 Comment(3)
Is there a VB.net version of this?Chymotrypsin
Be awesome if you could extend this with conditional access as well eg variable1.variable2?.variable3 ??= value;Gar
This is not exactly as the author asked - more specifically this answers to subject question, but not the question body (author intention). But this is the answer I was looking for, thanks.Manofwar
N
64

You are looking for the C# coalesce operator: ??. This operator takes a left and right argument. If the left hand side of the operator is null or a nullable with no value it will return the right argument. Otherwise it will return the left.

var x = somePossiblyNullValue ?? valueIfNull;
Newborn answered 13/7, 2009 at 16:31 Comment(2)
This answer does not cover the all cases from the question (only partially). Notice, that there is "string.IsNullOrEmpty". So Empty case is not handled here.Laellaertes
upvoted because this was the answer I was looking for. (I just needed the null check)Lafrance
T
42

The coalesce operator (??) is what you want, I believe.

Tiphany answered 13/7, 2009 at 16:29 Comment(2)
Yep...but only because the default is "".Raveaux
Um, how so? One can use any expression to replace null with..Interpreter
H
30

My guess is the best you can come up with is

this.approved_by = IsNullOrEmpty(planRec.approved_by) ? string.Empty
                                                      : planRec.approved_by.ToString();

Of course since you're hinting at the fact that approved_by is an object (which cannot equal ""), this would be rewritten as

this.approved_by = (planRec.approved_by ?? string.Empty).ToString();
Haematocryal answered 13/7, 2009 at 16:33 Comment(0)
G
26

With C#6 there is a slightly shorter way for the case where planRec.approved_by is not a string:

this.approved_by = planRec.approved_by?.ToString() ?? "";
Gravely answered 7/7, 2016 at 15:6 Comment(0)
D
25

Use the C# coalesce operator: ??

// if Value is not null, newValue = Value else if Value is null newValue is YournullValue
var newValue = Value ?? YourNullReplacement;
Dendro answered 17/7, 2017 at 1:57 Comment(0)
R
14

To extend @Dave's answer...if planRec.approved_by is already a string

this.approved_by = planRec.approved_by ?? "";
Raveaux answered 13/7, 2009 at 16:33 Comment(2)
I'm not sure why this answer is the 8th most voted :/Whoopee
Finally a correct answer to the question asked.Cossack
C
3

To assign a non-empty variable without repeating the actual variable name (and without assigning anything if variable is null!), you can use a little helper method with a Action parameter:

public static void CallIfNonEmpty(string value, Action<string> action)
{
    if (!string.IsNullOrEmpty(value))
        action(value);
}

And then just use it:

CallIfNonEmpty(this.approved_by, (s) => planRec.approved_by = s);
Checkerbloom answered 24/8, 2017 at 14:0 Comment(0)
A
3

The accepted answer was correct in time, when it was given.

For people still finding this question: Today you can use the ??= Operator.

e.g:

private string _test = null;

private void InitIfNull(){
 _test ??= "Init";
}
Anther answered 23/9, 2021 at 12:13 Comment(0)
O
1

You can also do it in your query, for instance in sql server, google ISNULL and CASE built-in functions.

Overcast answered 13/7, 2009 at 17:19 Comment(0)
A
-4

I use extention method SelfChk

static class MyExt {
//Self Check 
 public static void SC(this string you,ref string me)
    {
        me = me ?? you;
    }
}

Then use like

string a = null;
"A".SC(ref a);
Attitudinarian answered 5/11, 2015 at 23:47 Comment(2)
I guess you mean but not easy to read and understand, is that so?Attitudinarian
Ups! You are absolutely right: Very short, but NOT easy to read and understand (at least if you are not used to this notation)Checkerbloom

© 2022 - 2024 — McMap. All rights reserved.