Home > Blockchain >  C#, is this "if... else..." block equivalent to one line of code using null-coalescing ope
C#, is this "if... else..." block equivalent to one line of code using null-coalescing ope

Time:04-01

I'm curious if this block of code:

//value is an object, maybe null, maybe not
if (value == null)
   item.PassageStimuliTitle = "";
else
   item.PassageStimuliTitle = value.ToString().Trim();

is equivalent to this line:

item.PassageStimuliTitle = (string)(value ?? value.ToString().Trim());

I've used if... else... for a long time, but recently came across the null-coalescing operator in C#. I've used it to prevent null exception errors for params passed in method calls. I think using it in the example above is equivalent, and condenses the code from 4 lines to 1. Thanks for reading. Curious to hear feedback.

I'm expecting the two examples to be equivalent, but curious if there's something I'm missing.

CodePudding user response:

No, the null-coalescing operator expression is not written correctly. a ?? b means "evaluate to b if a is null, otherwise evaluate to a". Therefore, your use of the null-coalescing operator will always produce a NullReferenceException if value is null - your code will try to evaluate value.ToString() when value is null.

Your use of ?? would translate to something like the following if statement, which I think you'd agree is quite non-sensical:

if (value == null) {
    item.PassageStimuliTitle = (string)value.ToString().Trim();
} else {
    item.PassageStimuliTitle = (string)value;
}

With certain assumptions, the if statement can be rewritten as:

item.PassageStimuliTitle = value?.ToString().Trim() ?? "";

This uses the null conditional operator ?.. If value is null, then the entire value?.ToString().Trim() expression is null, and hence the RHS of the ?? is evaluated. Otherwise, .ToString().Trim() is called on value.

CodePudding user response:

item.PassageStimuliTitle = value != null ? value.ToString().Trim() : "";

From @Charles Mager comment:

item.PassageStimuliTitle = value?.ToString().Trim() ?? ""

Is a better and clearer one-liner.

CodePudding user response:

You used ?? operator incorrectly. In this example:

result = left_value ?? right_value;

?? operator returns left_value if it is NOT null. If left_value is null, it returns right_value.

So, in your case, if variable value is of type object, it should be:

item.PassageStimuliTitle = (value ?? "").ToString().Trim();

Here is a successfully compiled code fiddle.

  • Related