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

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 .

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}}

# 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 →

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!

null conditional assignment c#

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.

C# - What is the "??=" null-coalescing assignment operator?

Almost 5 years ago I made a post on the null conditional operator (?:) in C#. Now I am following up with a series on different operators. This post is on the Null-coalescing assignment operator (??=).

The null-coalescing assignment operator makes it easy to assign a new value to a variable if it is null. It checks the left side operand and if it is null it assigns the right side operand to it. An example of this can be seen below where s is "SomeValue" and k is null therefore k becomes "SomeValue" when the ??=` operator is used:

Had k not been null it would have kept its value:

I hope you found this post on the ??= operator helpful, let me know what you think in the comments down below :)

More on operators from my blog:

  • C# - What is the [x..y] range operator?
  • C# - What is the "??" null-coalescing operator?
  • C# - What is the "??=" null-coalescing assignment operator?
  • C# - What is the difference between the | and || operator or & and && operator

Null Coalescing Operator in C#: Simplifying Null Checks

The null coalescing operator in C# is a useful tool for checking and assigning default values to variables. It simplifies the process of checking for null values and assigning a default value when necessary. The operator is represented by two question marks (??), and it returns the value of its left-hand operand if it is not null, otherwise it evaluates the right-hand operand and returns its result.

The null coalescing operator is often used in situations where a default value needs to be assigned to a variable if the original value is null. It is a concise way of writing an if-else statement that checks for null values. The operator is especially useful when working with nullable value types, as it eliminates the need for additional null checks.

Developers can also use the null coalescing assignment operator (??=) to assign a value to a variable only if it is null. This operator is a shorthand way of writing an if statement that checks for null values and assigns a default value if necessary. Overall, the null coalescing operator is a powerful tool in C# that simplifies the process of checking for null values and assigning default values to variables.

Table of Contents

Understanding Null Coalescing Operator in C#

The Null Coalescing Operator (??) is a useful operator in C# that allows developers to check for null values in an expression and assign a default value if the value is null. This operator is used to simplify code and make it more concise.

The syntax for the Null Coalescing Operator is as follows:

Here, the operator checks if expression1 is null. If it is, then expression2 is assigned to result . If expression1 is not null, then its value is assigned to result .

The Null Coalescing Operator can be used with both value types and reference types. When used with value types, the default value for the type is used as the default value. For example, if the type is int , the default value is 0. If the type is bool , the default value is false .

When used with reference types, the default value is null . For example, if the type is string , the default value is null . In this case, the operator checks if the string is null and assigns a default value if it is.

The Null Coalescing Operator can also be used in combination with the null-conditional operator (?.). This allows developers to check for null values in a chain of expressions. For example:

Here, the operator checks if expression1 is null. If it is, then expression3 is assigned to result . If expression1 is not null, then expression2 is evaluated. If expression2 is null, then expression3 is assigned to result .

In summary, the Null Coalescing Operator is a useful operator in C# that simplifies code and makes it more concise. It allows developers to check for null values in expressions and assign default values if necessary.

Working with Null Coalescing Operator

The null coalescing operator (??) is a useful tool in C# for handling null values. It allows developers to specify a default value to use when a variable is null, without having to write lengthy if-else statements.

To use the null coalescing operator, simply write the variable you want to check for null, followed by ?? and the default value you want to use if the variable is null. For example:

In this example, if the value variable is null, the result variable will be assigned the value of 0.

The null coalescing operator can also be used in combination with the null-conditional operator (?.) to simplify code even further. The null-conditional operator allows developers to check if an object is null before accessing one of its properties or methods. When used in combination with the null coalescing operator, it allows for concise and easy-to-read code.

In this example, if the person object is null or its Name property is null, the name variable will be assigned the value of “Unknown”.

It is important to note that the null coalescing operator only works with nullable value types or reference types. It cannot be used with non-nullable value types like int or double.

Overall, the null coalescing operator is a powerful tool for simplifying code and handling null values in C#. By using it in combination with the null-conditional operator, developers can write concise and easy-to-read code that handles null values gracefully.

Null Coalescing Operator and Types

The null coalescing operator (??) is a C# operator that is used to assign a default value to a variable if the variable is null. It is a shorthand way of writing an if-else statement that checks if a variable is null.

The null coalescing operator can be used with different types of operands, including nullable types and value types. When using the null coalescing operator with nullable types, the operator returns the value of the left-hand operand if it is not null, otherwise it returns the value of the right-hand operand.

When using the null coalescing operator with value types, the operator returns the value of the left-hand operand if it is not equal to the default value of the value type, otherwise it returns the value of the right-hand operand. For example, if the left-hand operand is an integer with a value of 0, and the right-hand operand is an integer with a value of 1, the operator will return 1.

The null coalescing operator can also be used with different types of variables, including reference types and struct types. When using the operator with reference types, the operator returns the value of the left-hand operand if it is not null, otherwise it returns the value of the right-hand operand. When using the operator with struct types, the operator returns a new instance of the struct type with the properties set to the values of the left-hand and right-hand operands.

It is important to note that the null coalescing operator cannot be used with non-nullable value types. If a non-nullable value type is used as the left-hand operand, the operator will not compile. However, the operator can be used with nullable value types, which allow the value type to be assigned a null value.

In summary, the null coalescing operator is a useful C# operator that can be used with different types of operands and variables. It allows for concise and readable code that assigns default values to variables when they are null.

Null Coalescing Operator and Extension Methods

The null coalescing operator (??) is a useful tool in C# that allows developers to assign a default value to a variable if it is null. However, the operator only works on simple objects and does not help if developers need to access a member of that object. This is where extension methods come in.

Extension methods allow developers to add functionality to existing classes without having to create a new class or modify the existing one. By using extension methods, developers can extend the functionality of the null coalescing operator to work on more complex objects.

For example, an extension method can be created to handle null values on an IEnumerable collection. This method can be used to return an empty collection instead of a null value, making it easier to work with the collection in subsequent code.

Extension methods can also be used in conjunction with other LINQ operators, such as where, select, and join, to create more complex queries. By extending the null coalescing operator to work with these operators, developers can create more robust and error-resistant code.

Overall, the combination of the null coalescing operator and extension methods can help developers write more efficient and effective code by handling null values more gracefully.

Null Coalescing Operator in SQL

The SQL Coalesce function returns the first non-null expression among its arguments. It is a useful tool for handling null values in SQL queries. The syntax for the Coalesce function is as follows:

The Coalesce function takes n expressions as arguments and returns the first non-null expression. If all the expressions are null, it returns null.

The Null Coalescing Operator (??) in C# is similar to the Coalesce function in SQL. It returns the value of its left-hand operand if it is not null, otherwise, it returns the value of its right-hand operand.

In SQL, the Coalesce function is often used in conjunction with the IsNull function to handle null values. The IsNull function returns the first expression if it is not null, otherwise, it returns the second expression.

The above SQL query will return the value of column1 if it is not null, otherwise, it will return the value of column2.

The Coalesce function can also be used to concatenate strings in SQL. For example, the following SQL query will concatenate the values of column1 and column2, separated by a space.

The above SQL query will return the concatenated value of column1 and column2, separated by a space. If either column1 or column2 is null, it will be replaced by an empty string.

Overall, the Coalesce function is a useful tool for handling null values in SQL queries. It can be used to return the first non-null expression among its arguments, concatenate strings, and handle null values in conjunction with the IsNull function.

Null Coalescing Operator and Conditional Operators

The null coalescing operator (??) is a useful operator in C# that can be used to provide a default value for a null value. It returns the left-hand operand if it is not null, otherwise, it returns the right-hand operand. This operator can be combined with conditional operators to make code more concise and readable.

The conditional operator (?:) is a ternary operator that evaluates a Boolean expression and returns one of two possible values depending on the result of the evaluation. It is right-associative, meaning that the right operand is evaluated before the left operand. This operator can be used to provide a default value for a null value, but it requires more code than the null coalescing operator.

The throw expression is a new feature in C# 7.0 that allows an exception to be thrown as an expression. This can be useful for providing a default value in case of an error. For example, if a database query fails, the throw expression can be used to return a default value instead of throwing an exception.

The FirstOrDefault method is a LINQ extension method that returns the first element of a sequence or a default value if the sequence is empty. This method can be used in combination with the null coalescing operator to provide a default value for a null value.

The ValueOrDefault method is a method that returns the value of a nullable value type or a default value if the value is null. This method can be used in combination with the null coalescing operator to provide a default value for a null value.

Overall, the null coalescing operator and conditional operators are powerful tools that can be used to make code more concise and readable. They can be combined with other features of C# to provide default values in case of errors or null values.

Null Coalescing Operator and Overloading

The null coalescing operator ?? in C# is a shorthand way of checking if a value is null and providing a default value if it is. It is often used to simplify code and make it more concise.

In C#, the null coalescing operator can be overloaded to provide additional functionality. Overloading the null coalescing operator allows the developer to define custom behavior when using the operator with different types of operands.

When overloading the null coalescing operator in C#, the operator keyword is used to define the operator. The left-hand operand must be of a nullable value type, while the right-hand operand can be of any type.

An example of overloading the null coalescing operator in C# is shown below:

In the example above, the null coalescing operator is overloaded for the int? and int types. The operator returns the value of the left-hand operand if it is not null, otherwise it returns the value of the right-hand operand.

It is important to note that overloading the null coalescing operator should be used with caution, as it can lead to unexpected behavior if not implemented correctly.

In addition to overloading the null coalescing operator, C# also provides the null-conditional operators ?. and ?[] , which can be used to safely access members of an object or array that may be null.

Overall, the null coalescing operator and overloading can be useful tools for simplifying code and providing custom behavior when working with nullable types in C#.

Related posts:

  • C# Ternary Operator: Simplify Conditional Expressions
  • Var Keyword in C#: Understanding Its Use and Benefits
  • How to Format a String in C#: Complete Guide
  • Nullable Reference Types In C# 8

Leave a Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

Study through a pre-planned curriculum designed to help you fast-track your DotNet career and learn from the world’s best collection of DotNet Resources.

Find us on social media:

As Featured On

null conditional assignment c#

Contact: [email protected]  | Phone Number: (973) 916-2695 | Address: 288 Rosa Parks Blvd, Paterson, New Jersey 07501, USA

Disclaimer: Efforts are made to maintain reliable data on all information presented. However, this information is provided without warranty. Users should always check the offer provider’s official website for current terms and details. Our site receives compensation from many of the offers listed on the site. Along with key review factors, this compensation may impact how and where products appear across the site (including, for example, the order in which they appear). Our site does not include the entire universe of available offers. Editorial opinions expressed on the site are strictly our own and are not provided, endorsed, or approved by advertisers.

2022 © DotNetCoreTutorials All rights reserved.

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

    null conditional assignment c#

  2. How to use Null Conditional Operator

    null conditional assignment c#

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

    null conditional assignment c#

  4. Null Conditional Operators

    null conditional assignment c#

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

    null conditional assignment c#

  6. C# Basics (#17)

    null conditional assignment c#

VIDEO

  1. Let's Talk

  2. Null Conditional Operators

  3. Nested if else statement in C programming

  4. C# Part 12 Conditional Statements and While , Do While , For and Foreach Loop

  5. Conditional and selected signal assignment statements

  6. C# Highlights

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

  5. 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.

  6. Null Handling in C# Using Null-Conditional and Coalescing Operators

    Combining Null-Conditional and Null-Coalescing Operators. These operators can be combined for more expressive and concise code. Example. int result = data ?. Length ?? -1; In this example, the null-coalescing operator is used with the null-conditional operator to check if the length is null. If length is not null, its value is used; otherwise ...

  7. 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; } }

  8. 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.

  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#

    77. The problem occurs because the conditional operator doesn't look at how the value is used (assigned in this case) to determine the type of the expression -- just the true/false values. In this case, you have a null and an Int32, and the type can not be determined (there are real reasons it can't just assume Nullable<Int32> ).

  11. C#

    The null-coalescing assignment operator makes it easy to assign a new value to a variable if it is null. It checks the left side operand and if it is null it assigns the right side operand to it.

  12. Null Coalescing Operator in C#: Simplifying Null Checks

    The null coalescing operator is often used in situations where a default value needs to be assigned to a variable if the original value is null. It is a concise way of writing an if-else statement that checks for null values. The operator is especially useful when working with nullable value types, as it eliminates the need for additional null ...

  13. Null-Coalescing Assignment Operator In C# 8.0

    In this article, we will learn how to use Null-coalescing assignment operator in C# and also check the updated requirements of Null-coalescing operator requirements.

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

  15. Learn about C# Operators and Their Uses

    Introduced in C# 6.0, the Null Conditional Operator ?. will immediately return null if the expression on its lefthand side evaluates to null, instead of throwing a NullReferenceException. ... Binary operators with assignment. C# has several operators that can be combined with an = sign to evaluate the result of the operator and then assign the ...

  16. c#

    Closed 3 years ago. I just noticed that property assignment is not allowed in combination with the null conditional operator. With methods is it not a problem at all though. I always thought that properties are just syntactic sugar for setter methods. item?.SetMarker(Marker.Start); // Perfectly fine.

  17. 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.

  18. 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.