Dot Net Tutorials

Null-Coalescing Assignment Operator in C#

Back to: C#.NET Tutorials For Beginners and Professionals

Null-Coalescing Assignment Operator in C# 8

In this article, I am going to discuss Null-Coalescing Assignment Operator in C# 8 with Examples. Please read our previous article where we discussed Indices and Ranges in C# 8 with Examples. C# 8.0 has introduced a new operator that is known as a Null-Coalescing Assignment Operator (??=).

Null-Coalescing Assignment Operator (??=) in C# 8

C# 8.0 introduces the null-coalescing assignment operator ??= . We can use this ??= operator to assign the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null. That means the null-coalescing assignment operator ??= assigns a variable only if it is null. The syntax is given below.

Here, a is the left and b is the right operand of the null-coalescing operator ??=. If the value of a is null, then the ??= operator assigns the value of b in a. If the value of a is not-null, then it does not evaluate b.

It simplifies a common coding pattern where a variable is assigned with a value if it is null. For a better understanding, please have a look at the below diagram. Here, you can observe before C# 8, how we are checking null and assigning a value if it is null and how we can achieve the same in C# 8 using the null-coalescing assignment (??=) operator.

Null-Coalescing Assignment Operator in C# 8 with Examples

Points to Remember While working with ??= in C#:

  • The left-hand operand of the ??= operator must be a variable, a property, or an indexer element.
  • It is right-associative.
  • You cannot overload ??= operator.
  • You are allowed to use the ??= operator with reference types and value types.

Null-Coalescing Assignment Operator Example in C#:

Let us see an example for a better understanding. The following example is self-explained, so please go through the comment lines for a better understanding.

Null-Coalescing Assignment Operator Example in C#

Real-Time Use Cases of Null-Coalescing Assignment Operator

With the help of Null-Coalescing Assignment ??= Operator, we can remove many redundant if-else statements and make our code more readable and understandable. Let us understand this with an example. Here, first, I will show you an example using the if statement, and then I will convert the same example using Null-Coalescing Assignment ??= Operator so that you will get a better idea.

Example using If Statements:

Same example using null-coalescing assignment = operator:.

In the next article, I am going to discuss Unmanaged Constructed Types in C# 8 with Examples. Here, in this article, I try to explain Null-Coalescing Assignment in C# 8 with Examples. I hope you enjoy this Null-Coalescing Assignment in C# with Examples article.

dotnettutorials 1280x720

About the Author: Pranaya Rout

Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • .NET Framework
  • C# Data Types
  • C# Keywords
  • C# Decision Making
  • C# Delegates
  • C# Constructors
  • C# ArrayList
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
  • Range Structure in C# 8.0
  • Finding the Index of First Element of the Specified Sequence in C#
  • Finding the Start Index of the Specified Range in C#
  • Range Constructor in C#
  • Index Struct in C# 8.0
  • Static Local Function in C# 8.0
  • How to check whether the index is from start or end in C#?
  • Finding the End Index of the Specified Range in C#
  • Switch Expression in C# 8.0
  • Finding the Index which Points Beyond the Last Element in C#
  • Creating an Index From the Specified Index at the Start of a Collection in C#
  • Creating an Index From the End of a Collection at a Specified Index Position in C#
  • Getting the Hash Code of the Specified Range in C#
  • Finding all the Elements of a Range from Start to End in C#
  • How to Create a Range From a Specified Start in C#?
  • How to Create a Range to a Specified End in C#?
  • Interpolated Verbatim Strings in C# 8.0
  • Checking the Given Indexes are Equal or not in C#
  • Range and Indices in C# 8.0

Null-Coalescing Assignment Operator in C# 8.0

C# 8.0 has introduced a new operator that is known as a Null-coalescing assignment operator( ??= ). This operator is used to assign the value of its right-hand operand to its left-hand operand, only if the value of the left-hand operand is null. If the left-hand operand evaluates to non-null, then this operator does not evaluate its right-hand operand.

Here, p is the left and q is the right operand of ??= operator. If the value of p is null, then ??= operator assigns the value of q in p. Or if the value of p is non-null, then it does not evaluate q.

Important Points:

  • The left-hand operand of the ??= operator must be a variable, or a property, or an indexer element.
  • It is right-associative.
  • You cannot overload ??= operator.

Please Login to comment...

Similar reads.

author

  • 10 Best Free Note-Taking Apps for Android - 2024
  • 10 Best VLC Media Player Alternatives in 2024 (Free)
  • 10 Best Free Time Management and Productivity Apps for Android - 2024
  • 10 Best Adobe Illustrator Alternatives in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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-Coalescing ?? And Null-Coalescing Assignment ??= Operators in C#

Posted by Code Maze | Updated Date Nov 8, 2023 | 0

Null-Coalescing ?? And Null-Coalescing Assignment ??= 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 are going to find out what null-coalescing operator ?? and null-coalescing assignment ??= operators are and how to use them.

Let’s dive in!

Null-Coalescing Operator in C#

The null-coalescing operator is a C# operator consisting of two question marks ?? . The usage of the ?? operator allows for checking if the value of a given variable is null and if yes, we can return a default value instead. 

Become a patron at Patreon!

Let’s try to explain it with a simple example.

Imagine, we have two variables: userInput , which stores data collected from a user, and defaultValue . In the expression userInput ?? defaultValue , if userInput is not null , then the result is userInput , otherwise, the result is defaultValue . The defaultValue variable is evaluated only if userInput doesn’t have value.

Let’s see how we could code this behavior without the usage of the null-coalescing operator.

For that purpose, we will create a method that calculates the yearly income:

Alternatively, we could write this with the usage of the ternary operator :

Already better than the first option, but with the usage of the ?? operator, we can rewrite this method in an even shorter and simpler way:

Looks much cleaner now.

Null-Coalescing Assignment Operator in C#

Now that we know the ?? operator, understanding the null-coalescing assignment operator should be quite simple to explain.

Thanks to the ??= operator we can check if a given variable is null , and if so, we can assign a different value to it.

Let’s have a look at how to use it in practice.

This time we want to calculate monthly income, based on the hourly wage and number of working hours in the month. Both parameters are of type int? . If null happens, we want to take the average values for both variables:

The usage of the null-coalescing assignment operator allows us to make the method shorter and cleaner:

Again the code is more concise and cleaner.

Null-Coalescing Operators’ Associativity

The null-coalescing and null-coalescing assignment operators are right-associative . In other words, they are evaluated in order from right to left.

What does it actually mean and how can we use this?

Imagine, we want to evaluate yearly income based on average quarterly earnings. Of course, we would like to calculate it based on the most recent data. The problem is that for some reason, we don’t always have up-to-date values. In that case, we want to calculate it based on one of two previous quarters (but of course, we always want to have the most recent data):

currentQuarter ?? pastQuarter1 ?? pastQuarter2

Under the hood, the expression is evaluated to:

currentQuarter ?? (pastQuarter1 ?? pastQuarter2)

We check if we have data for the current quarter, if not – we check the previous quarter, and if it is also a null , we check even earlier quarter.

Of course, we can create such expressions for as many parameters as we want. As a result, we will always receive the first non-null value. 

How Do We Use Null Coalesce in C#?

As we have seen in the previous examples, in cases where a variable can be null or an expression can return a null operator ?? allows us to assign a default value or evaluate another expression .

Another interesting application can be a validation process.

Imagine, we don’t want to assign any default value, and null prevents the operation from being properly performed. In this case, by using the ?? operator we can check if a variable has a value and throw an exception if it doesn’t.

Let’s go back to calculating monthly income:

While the default value for the number of working hours per month makes sense, using the average salary may be quite inaccurate. So, when hourlyWage is null we throw an exception to let the user know that he needs to provide a valid value.

In this article, we have covered the null-coalescing and the null-coalescing assignment operators and the ways to use them.

guest

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

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

.net null coalesce assignment

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.

.net null coalesce assignment

Null Coalescing Operator (??) in C#

Null coalescing operator (??) is a C# operator, which is represented by the symbol ?? . It is generally used to set the default value of a variable. It takes two operands, if the left operand is null , then the right operand is returned else the left operand. 

It’s a precise way to say that “ If this value is NULL, then use the other value. “

This is an extension to the article on nullable types, If you haven’t gone through the article then please have a look at here.  Nullable Types in C#

Syntax of Null Coalescing Operator (??) in C#:

The null-coalescing operator has following syntax. 

First Expression ?? Second Expression (  If first expression is null , then evaluate the second expression. Otherwise evaluate first expression and ignore second expression )

For example:  x = y ?? z  // This implies, if y is null then assign z to x else assign y.

In the above example,

  • We have declared a nullable integer variable y  with null value as assigned.
  • In the next assignment statement, we are using coalescing operator and assigning 100 to x if y is null.
  • When we run above code, then it prints “The Value of ‘x’ is: 100” .

Usage of Null Coalescing Operator (??) in C#:

Null coalescing operator (??) will be handy while doing null check of a variable during assignment operation. let’s look at an example of null check in usual way.

Usual ways of Null check: 

Lets check an example of null check in usual way, in below sample code.

  • We have a function as GetInputFileName ( string [ ] args ) , it returns string value if input array has data or else returns null value.
  • In the main method, we retrieve the data in variable string inPutFile by calling the method.
  • Now, if inPutFile  is null then assign "InputFile.txt" or else assign inPutFile value to the fileName variable.

If you run above example, then you will get below output. 

Null Coalescing Operator_sample_1

In the above console, we get the default file name as "InputFile.txt" . Here, we performed usual ways of null checking and then assigned the default value. 

Null check using null coalescing operator (??):

We can use null coalescing operator (??) in above case to remove the extra null check and also can specify the default assignment in a single statement, as follows.

The complete sample code is as follows.

When you run above sample code, then you will get below output.

  • Here the value of inPutFile  variable is  null  and hence the default value of the variable FileName is being set to InputFile . txt  .

Null Coalescing Operator_sample_2

The null-coalescing operator can be used with a  reference type as well as nullable value types . Lets look at below example, how it works with nullable type.

Null coalescing operator (??) with Nullable Type:

Lets look at below code where we have used nullable value types.

In the above code snippet, we have declared a nullable type as int ? i   and a variable of type int as int j  

In above line of code,

  • We are using conditional operator (?:) to check if the nullable type has valid value or not.
  • If the variable i has some valid value, then assign it to variable j and if i is null then assign 100 to j   .
  • Here i  is a nullable value type and we have set the default to null , so when we run above code then it assigns 100 to variable j  .

This conditional check can be re-written using  (??) as follows.

In the above, compiler checks nullability of variable i  and then assigns 100 to variable  k .

Null Coalescing Operator_sample_3

Key Points:

  • It can be used in both reference types and nullable value types.
  • It works better with expressions and much easier to read and better to understand.

Thanks for your time 🙂 feel free to provide your feedback and do check my other blogs on Null-Conditional Operator in C# (?.)  and   Conditional Operator in C# (?.)

Share this:

One thought on “ null coalescing operator () in c# ”.

Add Comment

  • Pingback: Puzzle June 5, 2022 « Randy's Rants, Ravings and Reflections

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

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

DEV Community

DEV Community

Nick

Posted on Feb 7

Null Coalescing (??) Operator in C#

The C# Null Coalescing Operator (??) is a versatile operator that simplifies the handling of null values in C# code. It provides a concise way to specify a default value when a nullable variable is null, allowing you to write more concise and readable code.

To understand the Null Coalescing Operator, let's start with a simple scenario. Consider a variable called "name" that can either hold a string value or be null. If "name" is null, we want to assign a default value of "Anonymous" to it. Traditionally, we would use an if-else statement to achieve this:

With the Null Coalescing Operator (??), we can achieve the same result in a more concise way:

In the above code, the "?? " operator performs a null check on the left-hand side variable (in this case, "name"). If the left-hand side is null, the operator returns the right-hand side value ("Anonymous" in this case) and assigns it to the left-hand side variable.

The Null Coalescing Operator can be used with any nullable type, including reference types and nullable value types. This means it can handle null values for strings, integers, bools, and other types.

Let's take another example where we want to assign a default value to an integer variable (age) if it is null:

In this case, if the "age" variable is null, the Null Coalescing Operator assigns the value of "defaultAge" to "actualAge". Otherwise, it assigns the value of "age" itself.

In addition to assigning a default value, the Null Coalescing Operator can also be used to return a default value directly without assigning it to a variable. For example:

In the above code, if "favoriteColor" is null, the Null Coalescing Operator returns the default value ("Blue") directly without assigning it to a variable.

Overall, the C# Null Coalescing Operator (??) is a handy tool for simplifying null checks and providing default values in C# code. It helps to write more concise and readable code by reducing the number of if-else statements and adding clarity to null value handling.

Top comments (0)

pic

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

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

hamidmolareza profile image

🍳 Asynchronous Programming in C# Made Easy: Breakfast Included! ☕️

Hamid Molareza - Jan 16

tintin-bombona profile image

Gathering HAR and deciphered PCAP from you webdriver tests

Tintin Bombona - Jan 15

karenpayneoregon profile image

Dapper DateOnly/TimeOnly

Karen Payne - Jan 15

mohammadkarimi profile image

How DbContext pooling works!

Mohammad Karimi - Jan 15

DEV Community

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

This browser is no longer supported.

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

C# Language Highlights: Null Coalescing Assignment

Learn about Null Coalescing Assignment in short video from James and Maira .

Useful Links

  • ?? and ??= operators (C# reference)
  • Nullable Reference types
  • Understanding Nullable Reference Types
  • First steps with C #

Have feedback? Submit an issue here .

TecAdmin

Null Coalescing Operator (??) in C#

In the realm of C#, there are numerous operators that programmers use to perform various operations, and each operator has its unique functionality. One such operator, often seen as a significant utility in managing null values, is the Null Coalescing Operator (??).

What is the Null Coalescing Operator?

The Null Coalescing Operator is a binary operator that simplifies checking for null values and defining a default value when a null value is encountered. Its general syntax is as follows:

Here, `variable1` and `variable2` are the operands. The operator `??` checks if variable1 is null. If variable1 is not null, it returns variable1; otherwise, it returns variable2.

The Null Coalescing Operator serves as a more succinct way to use the ternary conditional operator for null checks. For example, `variable1 != null ? variable1 : variable2` is equivalent to `variable1 ?? variable2` .

Why Use the Null Coalescing Operator?

In programming, especially in a language like C# that allows null references, it’s common to have to check if a variable is null before performing operations on it. If you don’t, and you try to use a null object, you’ll get a NullReferenceException at runtime.

The Null Coalescing Operator simplifies this process by providing a concise, readable way to handle these null checks. It also enhances the clarity and maintainability of the code.

Using the Null Coalescing Operator in C#

To get a better understanding of how the Null Coalescing Operator works, let’s look at a practical example:

In this example, the name variable is null. The Null Coalescing Operator checks if name is null, and since it is, the operator returns defaultName. Therefore, “John Doe” is assigned to displayName , and “John Doe” is written to the console.

Now let’s see what happens when the name variable is not null:

In this case, the name variable is not null. Therefore, the Null Coalescing Operator returns name, and “Jane Doe” is assigned to displayName. The console then outputs “Jane Doe”.

Null Coalescing Operator with Nullable Value Types

The Null Coalescing Operator can also be used with nullable value types. Let’s take a look at an example:

Here, score is a nullable integer and is null. The Null Coalescing Operator checks if score is null and, since it is, the operator returns `defaultScore` . Therefore, 50 is assigned to `finalScore` , and 50 is printed to the console.

Null Coalescing Assignment Operator (??=)

C# 8.0 introduced a related operator: the Null Coalescing Assignment Operator ( ??= ). This operator performs a null check and assigns a default value to the variable if it’s null.

Here’s how you could use it:

In this case, because name is null, “John Doe” is assigned to name, and “John Doe” is printed to the console.

To summarize, the Null Coalescing Operator ( ?? ) and the Null Coalescing Assignment Operator ( ??= ) are powerful tools in C# that allow for more readable, concise, and maintainable code when dealing with null checks. With their help, programmers can effectively avoid null reference exceptions and make their code more robust.

Related Posts

How to unpack .xz and tar.xz files: a simple guide, creating a bash script to identify the last day of the month, step-by-step guide: installing docker on windows 11 and 10.

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

Type above and press Enter to search. Press Esc to cancel.

.net null coalesce assignment

dotNetTips.com

Improving Code Quality… One Developer at a Time

General Performance Tip: Null Coalescing Assignment

C# 8 introduced a novel method for performing null coalescing assignments, as illustrated below.

Before C# 8, the code for this operation appeared as follows.

Benchmark Results

Let’s examine the performance of various approaches to coding null coalescing. Previously, the performance difference between these two methods for coding null coalescing was negligible. However, as evident from these results, in .NET 8, utilizing the traditional approach for null checking proves to be slightly more performant.

.net null coalesce assignment

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

Type your email…

© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.

Please Share This:

  • Share on Tumblr

' src=

Published by dotNetDave

I live in San Diego, Ca USA View all posts by dotNetDave

Leave a comment Cancel reply

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

Discover more from dotNetTips.com

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

Continue reading

' src=

  • Already have a WordPress.com account? Log in now.
  • Subscribe Subscribed
  • Copy shortlink
  • Report this content
  • View post in Reader
  • Manage subscriptions
  • Collapse this bar

You must be logged in to post a comment.

  • Blogs by Topic

The .NET Tools Blog

Essential productivity kit for .NET developers

  • Guide Guide

Collection Expressions – Using C# 12 in Rider and ReSharper

Matthias Koch

Welcome to our series, where we take a closer look at the C# 12 language features and how ReSharper and Rider make it easy for you to adopt them in your codebase. If you haven’t yet, download the latest .NET 8 SDK and update your project files !

In this series, we are looking at:

  • Primary Constructors
  • Interceptors
  • Alias Any Type
  • Collection Expressions

This third part is all about collection expressions and how you can take full advantage of them with ReSharper and Rider!

Background and Syntax

In C#, we use many different types to represent collections, with various ways to create and initialize them. Many have verbose syntax, while some come with performance drawbacks, and together they make for a jumble of inconsistent code styles ( ToList vs. ToArray , IEnumerable<T> vs. params T[] , etc.). That’s plenty of motivation to sort it out and catch up with other languages like TypeScript or Python, which already successfully provide a succinct syntax. Some of the foundation for matching and deconstruction was already laid with the introduction of list patterns in C# 11 . With C# 12, we can also enjoy the power of construction!

Let’s compare how collections were constructed before C# 12 and how much cleaner they can be written now:

Since collection literals are target-typed , we cannot use var but must declare the type name for our variable. You can also see how the .. spread operator is used on the first array to integrate it into a new array with additional elements. Note that spreading could also be used between two elements.

IL Code and Conversion of Collection Expressions

You can use collection expressions to create collections for the most well-known collection types. The compiler automatically converts them to the appropriate target type:

Diving deeper into the low-level C# code generated by the compiler is always interesting. Feel free to take a look at our SharpLab snippet or to spin up the IL Viewer in ReSharper/Rider on your own solution to inspect some of these collection expressions:

Note that when the target type is IReadOnlyList<T> or IEnumerable<T> , using collection expressions comes with an additional allocation cost. In the following example, the compiler would allocate an array object for storage but also wrap this array into a compiler-generated collection class which forbids modifications at runtime:

Collection expressions also solve the issue of conversion where elements of a collection are more derived than the target’s scalar type. While the compiler initializes the collection, it implicitly takes advantage of assignment compatibility and conversion operators :

Supporting Collection Expressions on Custom Types

Similar to the duck-typing approaches for awaiting , iterating , or deconstructing objects, you can support collection expressions for your own types ! Assuming your type is a collection type, you just need to add the CollectionBuilderAttribute and provide a create method :

Do you have an interesting use case? Please let us know in the comments!

Conversion and Simplification

As with many new language features, you may find yourself eager to quickly integrate them into your daily coding routines and establish new habits. You might also feel compelled to convert the entire codebase to use these shiny additions. Unsurprisingly, ReSharper and Rider have you covered!

You can use the Use collection expression quick-fix to convert arrays, lists, and other collection-like objects to the new, more succinct syntax:

The quick-fix also takes Add calls below the initializer into account:

Of course, you can apply this quick-fix in bulk to save space and cognitive load throughout your solution, project, or file:

The bulk-fix may also bring you some peace of mind by unifying the various ways of passing empty collections :

Conversion Limitations

There are situations that ReSharper and Rider will handle more pessimistically to avoid possible runtime errors. At first, it might look like a good idea to convert the following method to use collection expressions:

However, we must anticipate that the caller may take advantage of the implementation and cast the results to a List<int> . In this case, converting to a collection expression would break the code with an InvalidCastException .

Code Style and Formatting

Every team has its unique taste regarding how code should be styled and formatted. ReSharper and Rider help you enforce your particular style through the Reformat Code action! As part of our collection expressions support, we’ve added new code style settings under some categories, like under the Line Breaks and Wrapping section:

Or under the Tabs, Indents, Alignment section:

You can try these new settings by selecting a code block and invoking the Configure code style action. Alternatively, you can grab the following snippet and adapt the formatter comments:

Future Work

We’re not done! We are still working on additional quick-fixes and context actions to make conversion easier for you. For example, we will support conversion for ToList , ToArray , and AsReadOnly invocations as well as simplifications to nested collection expressions.

In this post, we discovered several features related to the new C# 12 collection expressions. Try ReSharper 2024.1 EAP or Rider 2024.1 EAP to get the most out of the latest C# 12 in your daily work! If you see any opportunities for additional support, please let us know in the comments below!

Subscribe to a monthly digest curated from the .NET Tools blog:

By submitting this form, I agree that JetBrains s.r.o. ("JetBrains") may use my name, email address, and location data to send me newsletters, including commercial communications, and to process my personal data for this purpose. I agree that JetBrains may process said data using third-party services for this purpose in accordance with the JetBrains Privacy Policy . I understand that I can revoke this consent at any time in my profile . In addition, an unsubscribe link is included in each email.

Thanks, we've got you!

Discover more

dotInsights | April 2024

dotInsights | April 2024

Welcome to dotInsights by JetBrains! This newsletter is the home for recent .NET and software development related content. Featured Content This month, we bring you featured content from Dennis Dietrich! Dennis Dietrich is a manager at Phoenix Contact's Industrial Cabinet Solutions (ICS) busin…

Rachel Appel

The Rider 2024.1 Release Candidate Is Now Available

There’s only a few days left before the next major release for Rider! Don’t feel like waiting? Get a sneak peek of Rider 2024.1 now by downloading the Release Candidate build that has just landed on our website. The Release Candidate build contains all of the notable changes that we’ve introduc…

Sasha Ivanova

The ReSharper 2024.1 Release Candidate Is Now Available

Get a preview of all the latest features and improvements set to be shipped with the next major ReSharper and .NET tools releases by downloading the Release Candidate builds that have just landed. Here are the major improvements in each of the new builds: The ReSharper 2024.1 Release Can…

Sirenix’s Odin Inspector Support Comes to Rider, a JetBrains IDE

Sirenix’s Odin Inspector Support Comes to Rider, a JetBrains IDE

JetBrains Rider now recognizes Odin serialization, provides code analysis for grouping attributes, offers color pickers for color attributes, and more.

Anastasia Kazakova

Simple Is Not Easy

C# 語言特性更新 - c# 8.

C# 各版本新特性摘要,包含自己的想法與實務上的偏好。

唯獨成員 (Readonly members)

允許在結構 (struct) 成員上單獨使用 readonly 修飾詞。 其中有一些精細的限制,違反的話會有 Warning 或因而無法編譯,所以不用刻意去記。

預設介面方法 (Default interface methods)

介面中可以有預設實作方法,打破以前介面無法實作的限制。 主要的優點是讓 API 開發者可以在後續版本上加上新的介面方法而不會造成破壞性變更 (Breakin Changes),算是方便但是預設介面方法有很多限制,並不是表面上的 “介面中的方法可以有實作內容” 這麼單純,這個之後再另外發文探討。而這個特性除了方便外,也會讓介面和抽象方法之間的界線更為模糊,這時候設計的時候就應該更從物件導向設計的角度來決定兩者的使用時機,而不單單只是看語言特性的差異。

擴大模式比對的應用 (More patterns in more places)

模式比對從 C# 8 後更新的非常迅速,五花八門琳瑯滿目的很多,如果不是要看變更歷程的話,推薦直接看完整教學:

  • Pattern matching overview

switch 運算式 (Switch expressions)

這不只是語法外觀的改變,switch 區塊的主體也變成了運算式 (Expression),而不是以前的陳述式 (Statement)。

屬性模式 (Property patterns)、Tuple 模式 (Tuple patterns)、位置模式 (Positional patterns)

雖然命名上是 Property patterns,但他的意思不是在 Property 上使用模式比對,而是使用模式比對時可以針對目標型別的屬性來比對。大概就是用一堆符號來表達對屬性的型別、值範圍等判斷,主訴是程式碼的簡潔。

Tuple 模式和位置模式依此類推。

using 宣告 (Using declarations)

如上範例註解所示,在新的語法中我們不用關心區塊,區塊範圍會在編譯時期決定,但相對的就是要注意 using 宣告的變數應該盡早使用,避免在中間放其他無關程式碼造成實際的 using 區塊太大。

靜態區域函式 (Static local functions)

靜態區域函式能讓我們的區域函式不捕捉外層的變數,但這部分是透過 Warning CS8421 來達到的。

區域函式的變數捕捉特性會產生關注點發散到外層方法的副作用,又因為預設會自動捕捉外層的變數導致平常開發時很難確保所需資訊都由參數列提供而不是透過變數捕捉,靜態區域函式的特點可以有效避免這個困擾。

ref struct 可實作 IDisposable (Disposable ref structs)

就字面上的意思,同時也適用 readonly ref struct 。

可為 Null 的參考型別 (Nullable reference types)

參考型別本來就可以是 Null,這個特性使得參考型別編譯時被視為不可為 Null,並由編譯器分析是否可能誤用使其值為 null 。 看起來是在空值判斷這個議題上,透過強制規範迫使開發者嚴格檢視空值情境,如果在已有嚴格規範的專案上使用有錦上添花的效果,但如果現有專案規範與品質不夠或開發習慣不嚴謹,啟用這個特性幫助不大,甚至適得其反讓程式碼風格更不一致。

非同步資料流 (Asynchronous streams)

雖然名字有 streams 字眼,但他和 Stream 型別無關,是提供非同步迭代的一種特性。

如下方範例程式,有幾個關鍵:

  • 回傳 IAsyncEnumerable<T>
  • 呼叫端迭代時需要在前面加 await 關鍵字,不限定使用 foreach 的情境,在自己操作迭代器的情境也適用如 await using var enumerator = numberGenerator.GetAsyncEnumerator(); 。

IAsyncDisposable (Asynchronous disposable)

如字面上的非同步 dispose,上面的非同步資料流中提到的 IAsyncEnumerable<T> 就繼承自 IAsyncDisposable 。

索引和範圍 (Indices and ranges)

用更簡潔的語法表達索引和範圍,提供兩個新的型別 System.Index 和 System.Range ,並透過 ^ (倒數) 和 .. (到) 符號來使用。 要注意的是第一個是 0 ,但倒數第一個是 ^1 。

  • ^n 是倒數第 n 個 (即 sequence[sequence.Length - n] 的概念)。
  • x..y 是索引 x (包含) 到索引 y (不包含),省略 x 代表從頭開始。省略 y 代表到底為止。 x 和 y 可以是 ^m 和 ^n 這樣表示。 索引 x 必須小於或等於索引 y,而 ^m 和 ^n 推論成 x 和 y 後亦同。

雖然正向和倒數可以混用,但不要濫用不然可讀性也會差。

??= (Null-coalescing assignment)

非託管結構型別 (unmanaged constructed types).

如果結構只包含非託管型別的屬性時,該結構也是非託管型別。

巢狀運算式中的 Stackalloc (Stackalloc in nested expressions)

擴充內插逐字字串 (enhancement of interpolated verbatim strings).

可支援 $@"..." 和 @$"..." ,順序不會造成編譯錯誤。

What’s new in C# 8.0 (原文件已經被刪除,這是 Archive 網站的存檔)

IMAGES

  1. Null-Coalescing Assignment Operator in CSharp

    .net null coalesce assignment

  2. Handling the NULL Values Effectively with the SQL COALESCE Function for

    .net null coalesce assignment

  3. Handling the NULL Values Effectively with the SQL COALESCE Function for

    .net null coalesce assignment

  4. ISNULL vs COALESCE

    .net null coalesce assignment

  5. NVL, NVL2, NULL IF, COALESCE functions with examples

    .net null coalesce assignment

  6. Handling the NULL Values Effectively with the SQL COALESCE Function for

    .net null coalesce assignment

VIDEO

  1. Let's Talk

  2. Understanding ??= Null Coalescing Assignment Operator

  3. Null Coalescing in Apex ❓❓

  4. Dynamic Dispatch

  5. Introduction to Net Centric Computing

  6. Dealing with NULLs in SQL: Beginner's Guide to Using COALESCE

COMMENTS

  1. ?? and ??= operators

    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.

  2. Practical purpose of the null-coalescing assignment operator in C#?

    Nulls in C#. One of the new C# features allows us to get rid of nulls in our code with nullable reference types.We are encouraged to add <Nullable>enable</Nullable> to the project file due to problems like described here.. Of course, a lot of existing projects don't want to add this.

  3. Null-Coalescing Assignment Operator in C#

    Here, in this article, I try to explain Null-Coalescing Assignment in C# 8 with Examples. I hope you enjoy this Null-Coalescing Assignment in C# with Examples article. Dot Net Tutorials. About the Author: Pranaya Rout. Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft ...

  4. Null-Coalescing Assignment Operator in C# 8.0

    A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

  5. Null-Coalescing ?? And Null-Coalescing Assignment ??= Operator

    Null-Coalescing Operators' Associativity. The null-coalescing and null-coalescing assignment operators are right-associative. In other words, they are evaluated in order from right to left. What does it actually mean and how can we use this? Imagine, we want to evaluate yearly income based on average quarterly earnings.

  6. C#'s null-coalescing operator (??) explained · Kodify

    A typical way to use the null-coalescing operator is to assign a value to a reference variable. This way we can easily set our variable to another reference or, when that reference is null, use a default value instead. A code example of that is: // With the null-coalescing operator we check whether `csharpBook` is null.

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

  8. Null Coalescing Operator (??) in C#

    In the above example, We have declared a nullable integer variable y with null value as assigned. In the next assignment statement, we are using coalescing operator and assigning 100 to x if y is null.; When we run above code, then it prints "The Value of 'x' is: 100".; Usage of Null Coalescing Operator (??) in C#:

  9. 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. ... C# - What is the "??" null-coalescing operator? Almost 5 years ago I made a post on the null-conditional operator [https://peterdaugaardrasmussen ...

  10. Null Coalescing (??) Operator in C#

    In this case, if the "age" variable is null, the Null Coalescing Operator assigns the value of "defaultAge" to "actualAge". Otherwise, it assigns the value of "age" itself. In addition to assigning a default value, the Null Coalescing Operator can also be used to return a default value directly without assigning it to a variable. For example:

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

  12. C# Language Highlights: Null Coalescing Assignment

    C# Language Highlights: Null Coalescing Assignment. On .NET. Jul 8, 2021. Learn about Null Coalescing Assignment in short video from James and Maira.

  13. Null-Coalescing Assignment Operator

    In previous versions of C# like 7.3 we were using other different techniques to do the same task as performed by Null-coalescing assignment operator??. For instance, I'm using Null-coalescing operator to do the same but it seems a little bit cheap.

  14. Indices, Ranges, and Null-coalescing Assignments

    The new null-coalescing assignment is probably the most straightforward addition to the new C#8 language features. All it does is to simplify the common task of assigning a value if the field, property or variable in question is null. Previously, we could either use an if-statement with null-check or make use of the null-coalescing operator:

  15. C# Language Highlights: Null Coalescing Assignment

    Learn about Null Coalescing Assignment in short video from James and Maira.🏫 Free self-guided learning for C# on Microsoft Learn: https://aka.ms/learn/cshar...

  16. Null Coalescing Operator (??) in C#

    The Null Coalescing Operator simplifies this process by providing a concise, readable way to handle these null checks. It also enhances the clarity and maintainability of the code. Using the Null Coalescing Operator in C#. To get a better understanding of how the Null Coalescing Operator works, let's look at a practical example:

  17. c#

    Why can't you throw in a null-coalescing assignment operator in C#? 0. assigned null value in Null-coalescing assignmen C#. Hot Network Questions Why don't Airbus planes have perfectly smooth front sections? Procedural extrusion from an object Can privately administered colleges and universities in the USA successfully run without federal ...

  18. General Performance Tip: Null Coalescing Assignment

    In C# 8, a new method for null coalescing assignments was introduced, simplifying the code. Performance benchmark results show a slight advantage in using the traditional approach for null checking compared to the new method. Previously, the performance difference between the two methods was negligible.

  19. Collection Expressions

    Background and Syntax. In C#, we use many different types to represent collections, with various ways to create and initialize them. Many have verbose syntax, while some come with performance drawbacks, and together they make for a jumble of inconsistent code styles (ToList vs. ToArray, IEnumerable<T> vs. params T[], etc.).That's plenty of motivation to sort it out and catch up with other ...

  20. assigned null value in Null-coalescing assignmen C#

    It isn't for assigning null. Rather, it does a check for null and, if the checked variable is null, it assigns the righthand value. To better visualize what is happening, it helps to write out the longhand version of the null coalescing operator:

  21. C# 語言特性更新

    C# 各版本新特性摘要,包含自己的想法與實務上的偏好。 唯獨成員 (Readonly members) 允許在結構 (struct) 成員上單獨使用 readonly 修飾詞。 其中有一些精細的限制,違反的話會有 Warning 或因而無法編譯,所以不用刻意去記。

  22. C# Null coalesce with LINQ

    C# Null coalesce with LINQ. Ask Question Asked 8 years, 3 months ago. Modified 8 years, 3 months ago. ... which allows you to use the null-coalescing operator on the result. You can use the null-conditional operator as per Patrick's answer instead, but personally I'd prefer the code in this answer - I think it's simpler to understand. ...