This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

?? and ??= operators - the null-coalescing operators

  • 9 contributors

The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null ; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null. The null-coalescing assignment operator ??= assigns the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null . The ??= operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.

The left-hand operand of the ??= operator must be a variable, a property , or an indexer element.

The type of the left-hand operand of the ?? and ??= operators can't be a non-nullable value type. In particular, you can use the null-coalescing operators with unconstrained type parameters:

The null-coalescing operators are right-associative. That is, expressions of the form

are evaluated as

The ?? and ??= operators can be useful in the following scenarios:

In expressions with the null-conditional operators ?. and ?[] , you can use the ?? operator to provide an alternative expression to evaluate in case the result of the expression with null-conditional operations is null :

When you work with nullable value types and need to provide a value of an underlying value type, use the ?? operator to specify the value to provide in case a nullable type value is null :

Use the Nullable<T>.GetValueOrDefault() method if the value to be used when a nullable type value is null should be the default value of the underlying value type.

You can use a throw expression as the right-hand operand of the ?? operator to make the argument-checking code more concise:

The preceding example also demonstrates how to use expression-bodied members to define a property.

You can use the ??= operator to replace the code of the form

with the following code:

Operator overloadability

The operators ?? and ??= can't be overloaded.

C# language specification

For more information about the ?? operator, see The null coalescing operator section of the C# language specification .

For more information about the ??= operator, see the feature proposal note .

  • Null check can be simplified (IDE0029, IDE0030, and IDE0270)
  • C# operators and expressions
  • ?. and ?[] operators
  • ?: operator

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

c# conditional assignment null

Null-Conditional Operator in C# (?.)

Null conditional operator (?.) is another useful addition made to C# 6.0, it allows developers to write cleaner and concise code. We will explore more in detail.

In some situations, whenever you invoke a method or property on a object that is NULL . In that case, run-time throws a Null Referenc e exception. In-that situation you have to write explicit null-ability check of the object before invoking method or property.

To address the run-time null reference exception issue and to reduce the duplicate code for each null check , C#6.0 introduced null-conditional operator (?.) .

This operator (?.) verifies null ability of the operand before calling the method or property.

Syntax and usage of null conditional operator (?.) :

It uses a question mark ? and member access operator . (the dot) as follows.

expression1 ?. expression2  ( This  expression evaluates to  expression2 , if expression1 is Not-Null. else, it evaluates to null.)

Lets look at below example, In here, we have declared an Employee class. We are accessing employee property by doing a null check using ( Conditional operator (?:) ) as follows.

In the above example, this line string empName = ( emp != null ) ? emp . Name : null ; evaluates as, If emp  is Not NULL then assign emp . Name value to empName else assign NULL .

If you run above example then NULL value will be assigned to empName variable. Lets, re-write above statements using null-conditional operator (?.) as follows.

In the above example, we are using null-conditional operator (?.) to replace that extra NULL check condition. This code statement empName = emp ? . Name ; evaluates as, If emp  object is Not NULL  then invoke the property and assign emp . Name value to empName variable else assign NULL .

The usage of null-conditional operator  (?.) here allows cleaner  and concise code and also removed extra null conditional check. 

In below example, we have created an Employee instance as emp  and set emp . Name property value to “John” and emp . Age property value to 45 . We have set emp . PresentAddress property value to NULL .

When we run above sample code it will generate below out put.

Null-Conditional_Operator_1.3

You can see in the out put window, we are able to fetch Name and Age property value correctly using, However Address   properties are displayed as empty. Lets see why this happened here ? 

Here, we created a new Employee instance Employee emp = new Employee ( ) ; and assigned values to Name and Age properties. One thing you can note here is that, the emp  object is Not NULL , that’s why emp ? . Name and emp ? . Age evaluated to valid values.

In case of emp . PresentAddress , even though emp object is Not NULL  , but since we have set emp . PresentAddress = null , therefor the address properties emp ? . PresentAddress ? . City , emp ? . PresentAddress ? . State , emp ? . PresentAddress ? . Country and emp ? . PresentAddress ? . Zip weren’t evaluated and set to default empty value . 

Key Points to be noted :

Below points should be noted while using this operator (?.)

  • When you access an object property that returns value type , in that case null conditional operator (?.) will return nullable   version of that type.

For example, In below case, Age  property is a value type and emp ? . Age returns int ? ( nullable type of int ) and not an int . So while assigning it to a variable then you have to declare the variable as nullable type . In below case we have declared int ? employeeAge as Nullable type.

Null-conditional_Operator_1.0

It throws a compile error if you don’t specify the nullable type.

Null-conditional operator

  • You can chain multiple  null conditional operator (?.) in an expression , If the first operand is NULL , then the expression evaluation is short-circuited, and no further invocation within the call chain occurs. 

For example,  when we invoke emp ? . PresentAddress ? . State ; in below example code, then both PresentAddress and State property will be invoked only if emp is Not NULL  . If emp is NULL then no further call in the expression will occur.

Use of Null-Conditional Operator(?.) with Member Access operator (.)

If you club null conditional operator (?.) and member access operator (.) together, then during assignment expression the resulting expression will return NULL , if the left operand evaluates to NULL . However it will throw a  Null Reference Exception if the left operand of ( ? .) evaluates to NULL .

For example: emp ? . PresentAddress . State returns NULL when emp object is NULL . However emp . PresentAddress ? . State throws a  Null Reference Exception when emp object is NULL .

Share this:

2 thoughts on “ null-conditional operator in c# (.) ”.

Add Comment

“In that case, compiler throws a Null Reference exception.” should be run-time throws a Null Reference exception.

This line: string empName = (emp != null) ? emp.Name : null;

if best written as: string empName = null; if (emp != null) { empName = emp.Name; }

Why? Because you can add additional logic without altering the current lines. For example:

string empName = null; if (emp != null) { empName = emp.Name; // do a bunch of stuff here } else { // do a bunch of stuff here }

This is important for team environments with source code. It is not a contest to write code with the fewest characters. It is a contest to write code with can be modified with the least disruption.

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Discover more from

Subscribe now to keep reading and get access to the full archive.

Type your email…

Continue reading

As described in Chapter 3, while null can be a useful value, it also comes with a few challenges—namely, the need to check a value isn’t null before invoking the object’s member or changing the value from null to something more appropriate to the circumstance.

Although you can check for null using the equality operators and even the relational equality operators, there are several other ways to do so, including C# 7.0’s support for is null and C# 10.0’s support for is not null . In addition, several operators are designed exclusively for working with the potential of a null value. These include the null-coalescing operator (and C# 8.0’s null-coalescing assignment) and the null-conditional operator. There is even an operator to tell the compiler when you believe a value isn’t null even if it isn’t obvious to the compiler—the null-forgiving operator. Let’s start by simply checking whether a value is null or not.

It turns out there are multiple ways to check for null , as shown in Table 4.4 . For each listing, assume a declaration of string? uriString precedes it:

string ? uriString = null ;

Of course, having multiple ways to check whether a value is null raises the question as to which one to use. C# 7.0’s enhanced is null and C# 9.0’s is not null syntax are preferable if you are using a modern version of C#.

Obviously, if you are programming with C# 6.0 or earlier, the equality/inequality operators are the only option aside from using is object to check for not null . The latter has a slight advantage since it is not possible to change the definition of the is object expression and (albeit unlikely) introduce a minor performance hit. This renders is {} effectively obsolete. Using ReferenceEquals() is rare, but it does allow comparison of values that are of unknown data types, which is helpful when implementing a custom version of the equality operator (see “ Operator Overloading ” in Chapter 10).

Several of the rows in Table 4.4 leverage pattern matching, a concept covered in more detail in the “ Pattern Matching ” section of Chapter 7.

The null-coalescing operator is a concise way to express “If this value is null , then use this other value.” It has the following form:

expression1 ?? expression2

The null-coalescing operator also uses a form of short-circuiting. If expression1 is not null , its value is the result of the operation and the other expression is not evaluated. If expression1 does evaluate to null , the value of expression2 is the result of the operator. Unlike the conditional operator, the null-coalescing operator is a binary operator.

Listing 4.37 illustrates the use of the null-coalescing operator.

In this listing, we use the null-coalescing operator to set fileName to "config.json" if GetFileName() is null . If GetFileName() is not null , fileName is simply assigned the value of GetFileName() .

The null-coalescing operator “chains” nicely. For example, an expression of the form x ?? y ?? z results in x if x is not null ; otherwise, it results in y if y is not null ; otherwise, it results in z . That is, it goes from left to right and picks out the first non- null expression, or uses the last expression if all the previous expressions were null . The assignment of directory in Listing 4.37 provides an example.

C# 8.0 provides a combination of the null-coalescing operator and the assignment operator with the addition of the null-coalescing assignment operator . With this operator, you can evaluate if the left-hand side is null and assign the value on the righthand side if it is. Listing 4.37 uses this operator when assigning fullName .

In recognition of the frequency of the pattern of checking for null before invoking a member, you can use the ?. operator, known as the null-conditional operator , 4 as shown in Listing 4.38 . 5

The null-conditional operator example ( int? length = segments?.Length ) checks whether the operand (the segments in Listing 4.38 ) is null prior to invoking the method or property (in this case, Length ). The logically equivalent explicit code would be the following (although in the original syntax, the value of segments is evaluated only once):

int ? length =

     (segments != null ) ? (int?)segments.Length : null

An important thing to note about the null-conditional operator is that it always produces a nullable value. In this example, even though the string.Length member produces a non-nullable int , invoking Length with the null-conditional operator produces a nullable int ( int? ).

You can also use the null-conditional operator with the array accessor. For example, uriString = segments?[0] produces the first element of the segments array if the segments array was not null . Using the array accessor version of the null-conditional operator is relatively rare, however, as it is only useful when you don’t know whether the operand is null , but you do know the number of elements, or at least whether a particular element exists.

What makes the null-conditional operator especially convenient is that it can be chained (with and without more null-coalescing operators). For example, in the following code, both ToLower() and StartWith() will be invoked only if both segments and segments[0] are not null :

segments?[0]?.ToLower().StartsWith( "file:" );

In this example, of course, we assume that the elements in segments could potentially be null , so the declaration (assuming C# 8.0) would more accurately have been

string ?[]? segments;

The segments array is nullable, in other words, and each of its elements is a nullable string.

When null-conditional expressions are chained, if the first operand is null , the expression evaluation is short-circuited, and no further invocation within the expression call chain will occur. You can also chain a null-coalescing operator at the end of the expression so that if the operand is null , you can specify which default value to use:

string uriString = segments?[0]?.ToLower().StartsWith(

     "file:" ) ?? "intellitect.com" ;

Notice that the data type resulting from the null-coalescing operator is not nullable (assuming the right-hand side of the operator [ "intellitect.com" in this example] is not null —which would make little sense).

Be careful, however, that you don’t unintentionally neglect additional null values. Consider, for example, what would happen if ToLower() (hypothetically, in this case) returned null . In this scenario, a NullReferenceException would occur upon invocation of StartsWith() . This doesn’t mean you must use a chain of null-conditional operators, but rather that you should be intentional about the logic. In this example, because ToLower() can never be null , no additional null-conditional operator is necessary.

Although perhaps a little peculiar (in comparison to other operator behavior), the return of a nullable value type is produced only at the end of the call chain. Consequently, calling the dot ( . ) operator on Length allows invocation of only int (not int? ) members. However, encapsulating segments?.Length in parentheses—thereby forcing the int? result via parentheses operator precedence—will invoke the int? return and make the Nullable<T> specific members ( HasValue and Value ) available. In other words, segments?.Length.Value won’t compile because int (the data type returned by Length ) doesn’t have a member called Value . However, changing the order of precedence using (segments?.Length).Value will resolve the compiler error because the return of (segments?.Length) is int? , so the Value property is available.

Notice that the Join() invocation of Listing 4.38 includes an exclamation point after segments :

uriString = string .Join( '/' , segments ! );

At this point in the code, segments?.Length is assigned to the length variable, and since the if statement verifies that length is not null , we know that segments can’t be null either.

int ? length = segments?.Length;

if (length is not null && length != 0){ }

However, the compiler doesn’t have the capability to make the same determination. And, since Join() requires a non-nullable string array, it issues a warning when passing an unmodified segments variable whose declaration was nullable. To avoid the warning, we can add the null-forgiving operator ( ! ), starting in C# 8.0. It declares to the compiler that we, as the programmer, know better, and that the segments variable is not null . Then, at compile time, the compiler assumes we know better and dismisses the warning (although the runtime still checks that our assertion is not null at execution time).

Note that while the null-conditional operator checks that segments isn’t null, it doesn’t check how many elements there are or check that each element isn’t null.

In Chapter 1 we encountered warning CS8600, “Converting null literal or possible null value to non-nullable type,” when assigning Console.ReadLine() to a string . The occurs because Console.ReadLine() returns a string? rather than a non-nullable string . In reality, Console.ReadLine() returns null only if the input is redirected, which isn’t a use case we are expecting in these intro programs, but the compiler doesn’t know that. To avoid the warning, we could use the null-forgiving operator on the Console.ReadLine() return—stating we know better that the value returned won’t be null (and if it is, we are comfortable throwing a null-reference exception).

string text = Console.ReadLine() ! ;

The null-conditional operator is a great feature on its own. However, using it in combination with a delegate invocation resolves a C# pain point that has existed since C# 1.0. Notice in Listing 4.39 how the PropertyChanged event handler is assigned to a local copy ( propertyChanged ) before we check the value for null and finally fire the event. This is the easiest thread-safe way to invoke events without running the risk that an event unsubscribe will occur between the time when the check for null occurs and the time when the event is fired. Unfortunately, this approach is nonintuitive, and frequently developers neglect to follow this pattern—with the result of throwing inconsistent NullReferenceExceptions . Fortunately, with the introduction of the null-conditional operator, this issue has been resolved.

The check for a delegate value changes from what is shown in Listing 4.39 to simply

PropertyChanged?.Invoke(propertyChanged(

   this , new PropertyChangedEventArgs(nameof(Age)));

Because an event is just a delegate, the same pattern of invoking a delegate via the null-conditional operator and an Invoke() is always possible.

________________________________________

  • p.key == item.key) && !currentPage.some(p => p.level > item.level), }" > p.key == item.key) && !currentPage.some(p => p.level > item.level), }" :href="item.href"> Introduction
  • p.key == item.key) && !currentPage.some(p => p.level > item.level), }" > p.key == item.key), }" :href="item.href"> {{item.title}}

DEV Community

DEV Community

pushpk

Posted on Jun 15, 2020

Using NULL Conditional and Coalescing Operators in C#

Null checking is important part of developing quality code, Without it Code with throw NullReferenceException

Most common way to check for nulls is using If, consider below code

If we try to run this code, We will get NullReferenceException since there is no null checking in place inside DisplayPerson function

Now as soon as I get null exception, I go into code where NullReferenceException is causing and add if null check, like below

and adding if null check is fine except adding it in every method in code makes code verbose.

NULL-conditional Operator(?.)

Another way to solve this issue is to use null-conditional operator, ?. introduced in C# 6.0, here is how we can reduce if null check by using null-conditional operator

The part on the right of ? only evaluates if the part to the left is not null. Otherwise, the code returns null. In the case above, person?.FirstName and person?.LastName evaluates to null, but it does not throw an exception because there is no attempt to access a member on a null reference.

Use the null-conditional operator on members of namespaces, types, array elements (?.[]), access methods, or to invoke delegates.

Now this is good but what if we want some default value to be return if object is null, this is where Null-coalescing Operator ?? can be useful,

Null-coalescing Operator(??)

Null-coalescing Operator is a binary operator that simplifies checking for null values. it is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise, it returns the right operand.

In cases where a statement could return null, the null-coalescing operator can be used to ensure a reasonable value gets returned. This code returns the Firstname and Lastname of a person or the default names if the person is null. this operator is a handy tool when working with the null-conditional operator.

From C# 7, it is also possible to use the null-coalescing operator to shorten the validation of arguments, below code requires to validate name, here is how I would look

Using the null coalescing operator allows this to be shortened to the code below.

Checking NULL is vital part of code for stability, Using NULL-conditional and Null-coalescing Operator can really reduce and simplify code.

Happy Coding!

Top comments (1)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

peledzohar profile image

  • Location Israel
  • Work .Net Developer
  • Joined Sep 9, 2019

peledzohar image

The perfect non-null test

Zohar peled ・ nov 13 '19 ・ 2 min read.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

ssukhpinder profile image

Day 29 of 30-Day .NET Challenge: Generics & Custom Interfaces

Sukhpinder Singh - Apr 19

mikeyoung44 profile image

HanDiffuser: Text-to-Image Generation With Realistic Hand Appearances

Mike Young - Apr 23

syedbalkhi profile image

6 Tips for Creating Better Website Surveys

Syed Balkhi - Apr 22

qyrusai profile image

Dream Project to Build

Qyrus - Apr 19

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Code Maze

  • Blazor WASM 🔥
  • ASP.NET Core Series
  • GraphQL ASP.NET Core
  • ASP.NET Core MVC Series
  • Testing ASP.NET Core Applications
  • EF Core Series
  • HttpClient with ASP.NET Core
  • Azure with ASP.NET Core
  • ASP.NET Core Identity Series
  • IdentityServer4, OAuth, OIDC Series
  • Angular with ASP.NET Core Identity
  • Blazor WebAssembly
  • .NET Collections
  • SOLID Principles in C#
  • ASP.NET Core Web API Best Practices
  • Top REST API Best Practices
  • Angular Development Best Practices
  • 10 Things You Should Avoid in Your ASP.NET Core Controllers
  • C# Back to Basics
  • C# Intermediate
  • Design Patterns in C#
  • Sorting Algorithms in C#
  • Docker Series
  • Angular Series
  • Angular Material Series
  • HTTP Series
  • .NET/C# Author
  • .NET/C# Editor
  • Our Editors
  • Leave Us a Review
  • Code Maze Reviews

Select Page

Null-Conditional Operators in C#

Posted by Code Maze | Updated Date Apr 1, 2023 | 0

Null-Conditional Operators in C#

Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!

In this article, we will discuss a feature of C# known as null-conditional operators and how it can help prevent the occurrence of null-reference exceptions, which are commonly encountered by developers.

Let’s dive in!

What Are Null-Conditional Operators in C# and Why Are They Important?

Null-conditional operators were introduced in C# 6.0 to provide a way to simplify null-checking code and avoid null-reference exceptions . They also offer a safe way to access members and elements of an object  or collection that may be null .

Become a patron at Patreon!

The way they work is straightforward – if the object , or collection, is null , the operator returns null instead of throwing a NullReferenceException otherwise, they return the value.

Let’s set up our example:

In a new file, we create a simple Student class. It has two properties – Name and Courses as well as an Enroll method.

We have things ready, let’s dive in!

Safe Navigation Operator (?.) And (?[])

In our application, if objects, or their members, can be null we have to appropriately handle them:

Here, we first check if the student variable is null before printing its Name . Then we check if the Courses property is null before printing all courses to the console. We do this to guard our application against NullReferenceExpection . For simple code, this might be fine but for complex software, this becomes very tedious and lowers code readability.

The null-conditional operator for safe member access, ?. , and safe element access, ?[] , were introduced to tackle this problem:

Here, we don’t need to do if checks as the ?. and ?[] operators will return null if the object, or its members, are null :

We don’t get the student’s name or first course but our code compiles and runs without throwing exceptions.

The first thing to remember is that null-conditional operators are short-circuiting . This means that, if one operation in a series of member or element access operations returns null , the rest do not execute. In our example, we have student?.Courses?[2] , here if the student is null , we directly return null , without evaluating the rest of the expression.

The second thing we must remember is that null-conditional operators save us only from null-reference exceptions . A null-conditional operator cannot save us from a situation where student.Name or student.Courses are not null but throw an Exception . In practice, this means that if Courses is not null but index 2 is outside its bounds, an IndexOutOfRangeException will be thrown.

Null-Coalescing Operator (??) And (??=)

In some cases, not getting an Exception might do the trick. But we also have those cases where we need a default value to be returned:

We declare a name variable as an empty string. Then we check if the student ‘s Name is null , empty, or white space. If it is not we assign it to our name variable, else we assign John to it.

Here comes the null-coalescing operator, ?? :

var name = student?.Name ?? "John";

The initial ten lines of code are shortened to just one. The ?? operator will return the value on its left if it’s not null , otherwise, it returns the value on its right.

In other cases, we might want to assign a value to a variable, or a property of an object, if it’s null :

We check if the namelessStudent ‘s Name is null , empty, or white space. If it is we assign John to it.

The null-coalescing assignment operator, ??= , can improve our code:

namelessStudent.Name ??= "John";

Here, the ??= operator will assign the value John , to namelessStudent.Name if it is null.

Null-Conditional Invocation Operator (?.())

Often our reference-type objects have methods that we need to invoke safely:

Here, before we Enroll our student in Math class, we make sure that student is not null .

This type of check further bloats our code, but we can do something about it:

student?.Enroll("Math");

Like with the safe member access operator, the null-conditional invocation operator, ?.() , will only invoke the method if the object it belongs to is not null .

Thread Safety and Null-Conditional Operators

An essential concept in asynchronous programming is thread safety. Before we take a look at how null-conditional operators help with that, let’s expand our Student class:

We add a MaxNumberOfCourses constant and set it to 10 and an EventHandler called MaxNumberOfCoursesReached . Then we expand the Enroll method to invoke the event if the number of Courses reaches the limit and the MaxNumberOfCoursesReached is not null .

This is considered a thread-safe way of invocation due to the fact that if a different thread unsubscribes from our event and MaxNumberOfCoursesReached becomes null , it won’t be invoked and our object will remain unaffected.

Now, let’s utilize the null-conditional member access operator:

Here, we remove the if statement and use ?. before invoking MaxNumberOfCoursesReached – this reduces the code length but has the same result.

Advantages of Using Null-Conditional Operators

Every new feature in C# is there for a good reason, and the null-conditional operators make no difference. They make our code more concise and less exception-prone, especially when we deal with complex object structures that may contain null values.

Avoiding Null-Reference Exceptions

The most valuable advantage of using the null-conditional operators is making our application less prone to throwing null-reference exceptions. The return of null values may still be a nuisance but it is better than having our program crash. Moreover, if null values are handled appropriately, the end-user won’t even know that something unexpected has happened.

Simplifying Code and Better Code Readability

Simplifying our code has the advantage of improving its readability but also makes it easier for others to understand. This is very important as we often work in a team environment and understanding each other’s code is vital.

Disadvantages of Using Null-Conditional Operators

In this section, we will explore the potential disadvantages of null-conditional operators. By understanding the limitations and risks associated with them, we can decide when to leverage null-conditional operators and when to use alternative approaches for handling null values.

Decreasing Readability

Using null-conditional operators can help us reduce the amount of boilerplate code we use to handle null values. On the other hand, overusing them can make our code harder to read and understand, especially for developers who are not familiar with this feature of C#. This can lead to more time spent deciphering code and an increased probability of introducing errors.

Harder Debugging

Debugging code that heavily relies on null-conditional operators can be more challenging. It can be hard to determine which operator, or expression, is causing problems. Also, if a null-conditional operator is used improperly, it can lead to unexpected behavior that may be difficult to find and fix.

Not Present in Older Versions of C#

Null-conditional operators were introduced in C# 6.0, which means they are not an option for developers working with legacy code, or targeting older versions of the .NET Framework. This removes the possibility for some developers and teams to take advantage of those operators.

In this article, we learned about the different null-conditional operators in C#. Now, we know how and when to use them to prevent null-reference exceptions and improve our code readability. We have also learned about the potential disadvantages and how to avoid them.

guest

Join our 20k+ community of experts and learn about our Top 16 Web API Best Practices .

Grant Winney

Checking for null in C#, using the null-conditional and null-coalescing operators

Checking for nulls in C# is tedious, but C# 6 gave us the null-conditional and null-coalescing operators. Let's see how they've improved things.

Boy, that's a catchy title. Sometimes they just roll off the tongue, ya know? 🙄

Last week, I wrote about using string interpolation to craft readable strings , and figured it might be worth investigating some of the other useful additions to C# over the last few years. So let's check out new ways (well, new compared to C#'s age) to efficiently check for nulls.

Anyone who's spent some time in C# has had a run in with the dreaded NullReferenceException . The underlying cause isn't always obvious, but getting around it usually is - just check for nulls. Traditionally, the only way to safely use some deeply nested object was to check for null at every level, so a lot of older apps are littered with code like this:

That is just so long-winded and boring. We shouldn't have to type all that repetitive code out, and we don't. C# 6 gave us a couple new tools - the null-conditional and null-coalescing operators.

First, let's define a few nested classes to use for examples, and then a company with a couple departments and employees to experiment with. If you want to play around with the project I created, grab the code on GitHub .

Null Conditional operator

The null-conditional operator allows you to call a deeply-nested class member, where anything in the chain of objects might be null, and it returns null instead of throwing an exception.

In the above code, for example, the Company has a name. But what if it didn't, and you tried to get the length of it for some reason? It would throw an exception if you didn't check for null first. Null conditional operator to the rescue.

By adding a single ? to the second line in the right place, it stores null instead of throwing an exception. One caveat is that, even though Length returns an integer, the variable on the left is actually an int? , since it needs to be able to store null.

Here's another example, where one company has a URL, but the other does not. Since URL is null on the second line, accessing Host would normally throw an exception.

You only have to use them where you're worried about nulls too. If you've defined your classes in such a way that if there's a department, then it will have a collection of employees (maybe an empty one), then you can just use the null conditional operator in the one place you're worried about.

Note #1: The operator always applies to the variable right before it. So above, if Departments is null then you're safe. But if Departments is instantiated but empty, then trying to access the first element from the collection will still throw a different exception.

Note #2: Use these where it makes sense. I happen to think that, if there's no reasonable explanation for a certain variable to ever be null, then it's probably better to let it throw an exception so you can debug it, rather than aggressively preventing NullReferenceException everywhere and giving things default values where it doesn't make sense.

Null Coalescing operator

Using the null coalescing operator with the null conditional gives you even more power, but it's still concise enough for a single line. It lets you define what the default value should be when a value is null. For example, you can replace this:

Or even this:

Revisiting the earlier examples, you can use both together to avoid an exception and to decide what the value should be when it's null...

If you want to count the number of employees, but some departments won't have any, then use the null coalescing operator to just say there's 0 employees.

Here's one more example, where some employees don't have a hire date. Not sure why that would be, but out in space you've got bigger fish to fry than recording every alien who joins the crew. Or something.

And that example from the beginning? It becomes this:

If you found this content useful, and want to learn more about a variety of C# features, check out my GitHub repo , where you'll find links to plenty more blog posts and practical examples!

c# conditional assignment null

How to use TimeProvider and FakeTimeProvider (time abstraction in .NET)

What are generic attributes in c# 11, how to log messages to multiple targets with nlog.

# Null-conditional Operators

# null-conditional operator.

(opens new window) .

Class used in the following example:

If an object is potentially null (such as a function that returns a reference type) the object must first be checked for null to prevent a possible NullReferenceException . Without the null-conditional operator, this would look like:

The same example using the null-conditional operator:

# Chaining the Operator

The null-conditional operator can be combined on the members and sub-members of an object.

# Combining with the Null-Coalescing Operator

(opens new window) to provide a default value:

# The Null-Conditional Index

Similarly to the ?. operator, the null-conditional index operator checks for null values when indexing into a collection that may be null.

is syntactic sugar for

# Avoiding NullReferenceExceptions

This effect can be chained together:

# Null-conditional Operator can be used with Extension Method

(opens new window) , but you can use ?. to null-check anyway.

Normally, the method will be triggered for null references, and return -1:

(opens new window) :

This behavior is actually expected from the way in which the ?. operator works: it will avoid making instance method calls for null instances, in order to avoid NullReferenceExceptions . However, the same logic applies to the extension method, despite the difference on how the method is declared.

(opens new window) documentation.

  • X?.Y; //null if X is null else X.Y
  • X?.Y?.Z; //null if X is null or Y is null else X.Y.Z
  • X?[index]; //null if X is null else X[index]
  • X?.ValueMethod(); //null if X is null else the result of X.ValueMethod();
  • X?.VoidMethod(); //do nothing if X is null else call X.VoidMethod();

Note that when using the null coalescing operator on a value type T you will get a Nullable<T> back.

← Null-Coalescing Operator nameof Operator →

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Null-conditional assignment #6045

@RikkiGibson

RikkiGibson commented Apr 21, 2022 • edited

  • 👍 77 reactions
  • 👎 3 reactions
  • 🎉 7 reactions
  • ❤️ 17 reactions

@RikkiGibson

CyrusNajmabadi commented Apr 21, 2022

Sorry, something went wrong.

@quinmars

quinmars commented Apr 21, 2022

  • 👍 15 reactions

RikkiGibson commented Apr 21, 2022

  • 👍 3 reactions
  • 👍 4 reactions

@jnm2

jnm2 commented Apr 21, 2022

@jcouv

michael-hawker commented Apr 27, 2022

  • 👍 12 reactions
  • ❤️ 5 reactions

@michael-hawker

Duranom commented Aug 28, 2022

Cyrusnajmabadi commented aug 28, 2022, duranom commented aug 30, 2022, cyrusnajmabadi commented aug 30, 2022 • edited, rikkigibson commented aug 30, 2022 • edited.

  • 👍 2 reactions

@CaseyHofland

CaseyHofland commented Sep 9, 2022 • edited

@BillWagner

BillWagner commented Oct 10, 2022

Rikkigibson commented oct 10, 2022 • edited, rikkigibson commented oct 26, 2022, jnm2 commented oct 26, 2022, caseyhofland commented oct 27, 2022 • edited, billwagner commented nov 3, 2022, cyrusnajmabadi commented nov 3, 2022 • edited.

  • 👍 1 reaction

@SF-Simon

SF-Simon commented Mar 16, 2023

@HaloFour

HaloFour commented Mar 16, 2023

Sf-simon commented mar 16, 2023 • edited.

@manodasanW

tilkinsc commented Jan 19, 2024 • edited

@Rekkonnect

Rekkonnect commented Jan 19, 2024

@jamesford42

jamesford42 commented Jan 26, 2024

  • ❤️ 7 reactions

No branches or pull requests

@jamesford42

IMAGES

  1. C# Tutorial

    c# conditional assignment null

  2. C# : Conditional operator assignment with Nullable value types?

    c# conditional assignment null

  3. C# Null-Conditional Operator (? Operator) Explained!

    c# conditional assignment null

  4. Combining the Null Conditional and Null Coalescing Operators in C#

    c# conditional assignment null

  5. Null conditional (?. and ?[]) operators

    c# conditional assignment null

  6. C# : Null-conditional operator and string interpolation in C# 6

    c# conditional assignment null

VIDEO

  1. Let's Talk

  2. C++ Conditional Statement

  3. C# Conditional Statements _IF condition

  4. C# Conditional statement

  5. Nested if else statement in C programming

  6. Null Conditional Operators

COMMENTS

  1. ?? and ??= operators

    The ?? operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null. The null-coalescing assignment operator ... you can use the ?? operator to provide an alternative expression to evaluate in case the result of the expression with null-conditional ... see The null coalescing operator section of the C# ...

  2. c#

    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 :) .

  3. Null-Conditional Operator in C# (?.)

    Null conditional operator (?.) is another useful addition made to C# 6.0, it allows developers to write cleaner and concise code. We will explore more in detail. In some situations, whenever you invoke a method or property on a object that is NULL.In that case, run-time throws a Null Reference exception. In-that situation you have to write explicit null-ability check of the object before ...

  4. Essential C#: Programming with null

    These include the null-coalescing operator (and C# 8.0's null-coalescing assignment) and the null-conditional operator. There is even an operator to tell the compiler when you believe a value isn't null even if it isn't obvious to the compiler—the null-forgiving operator. Let's start by simply checking whether a value is null or not.

  5. Using NULL Conditional and Coalescing Operators in C#

    Null-coalescing Operator is a binary operator that simplifies checking for null values. it is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise, it returns the right operand. In cases where a statement could return null, the null-coalescing operator ...

  6. Null-Conditional Operators in C#

    The second thing we must remember is that null-conditional operators save us only from null-reference exceptions.A null-conditional operator cannot save us from a situation where student.Name or student.Courses are not null but throw an Exception.In practice, this means that if Courses is not null but index 2 is outside its bounds, an IndexOutOfRangeException will be thrown.

  7. C# Null Coalescing and Null Conditional Operators

    We used the null coalescing operator. With this operator, you can handle null references with less source code. The null coalescing operator is similar to the ternary operator. Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

  8. c#

    Following is the syntax for the conditional operator. Refering to ?? Operator (C# Reference) The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.

  9. Checking for null in C#, using the null-conditional and null-coalescing

    Null Conditional operator. The null-conditional operator allows you to call a deeply-nested class member, where anything in the chain of objects might be null, and it returns null instead of throwing an exception. In the above code, for example, the Company has a name. But what if it didn't, and you tried to get the length of it for some reason ...

  10. C#

    Null-conditional Operator can be used with Extension Method. Extension Method can work on null references, but you can use ?. to null-check anyway. public class Person { public string Name {get; set;} } public static class PersonExtensions { public static int GetNameLength(this Person person) { return person == null ? -1 : person.Name.Length; } }

  11. 3 ways to update C# variables conditionally · Kodify

    1) Set variable with if statement. 2) Update variable with if/else statement. 3) Set variable with conditional operator. Two quick ways to set variable conditionally. Replace if/else with default value. Replace if/else with conditional operator. Summary. Most variables have a different value at various stages in our program's execution. A ...

  12. C#'s conditional operator (?:) explained · Kodify

    ApplCount():0); Here we use the Console.WriteLine()method to print the number of appliances we need for an order. We base that count on the isKitchenBoolean variable. When that one is true, the conditional operator executes ApplCount()and returns that method's value. Should that variable be false, the operator returns 0.

  13. c#

    The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then, If X and Y are the same type, then this is the type of the conditional expression. Otherwise, if an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the ...

  14. Null-conditional assignment · Issue #6045 · dotnet/csharplang

    null_conditional_assignment: null_conditional_member_access assignment_operator expression : null_conditional_element_access assignment_operator expression. Neither of which match the above. As such, this is normal assignment. ... You don't have to do that in C#, and the idiomatic null check x != null or x is not null is generally more concise.

  15. c#

    There is no conditional operator that doesn't assign when null. An if is most suitable in this case ... Using the null-conditional operator on the left-hand side of an assignment. 0. ... c# shorthand for if not null then assign value. 0. Is there a way that I could assign a value to a variable at the same time as checking if it's null or not?

  16. C# Null Conditional Operator alternative (conditional assignment)?

    The C# null-conditional operator allows for useful short circuiting:. double? range = (unit as RangedUnit)?.WeaponRange; Unfortunately the null-conditional operator cannot be used in the same way for short hand assignment, because it returns a value (which cannot be used in left handed assignment):