Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 6.0 null operator in a conditional statement

Tags:

c#

null

c#-6.0

From what I gathered with the new null operator in C# 6.0 you can do something like this:

string name = people.FirstOrDefault()?.FullName;

And this is great, but one verification I often come across is something like this:

object name = null;
if(name != null) {
    DoSomething();
} else {
    DoSomethingElse();
}

Given the purpose of the new null operator, I would like something like this should be possible:

if(name?) {
    DoSomething();
} else {
    DoSomethingElse();
}

The problem here from what I understood is that when the value the ? is checking is in fact null, it returns null, and you need a bool condition for the if statement. Since you can't directly convert a null to a bool, is there a simpler way of checking this without doing if(name != null) using the new null operator in C# 6.0?

like image 684
Schrödinger's Box Avatar asked Aug 25 '15 15:08

Schrödinger's Box


People also ask

What do you mean by C?

C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is %d in C programming?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.


1 Answers

There's no point in doing this. You're not doing any null coalescing in your example - you're simply checking for null.

A better use would be if you wanted to check some member of the name object. For example:

if (name?.FirstName != null) ...

But as you can see, it's still a simple comparison for null - we just used null coalescing to avoid having to write something like this:

if (name != null && name.FirstName != null) ...
like image 118
Luaan Avatar answered Oct 23 '22 10:10

Luaan