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

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

  • How to Use ChatGPT with Bing for Free?
  • 7 Best Movavi Video Editor Alternatives in 2024
  • How to Edit Comment on Instagram
  • 10 Best AI Grammar Checkers and Rewording Tools
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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 *

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 .

C# 8 - Null coalescing/compound assignment

There are a lot of cool new features in C# 8 and one of my favorites is the new Null coalescing assignment operator.

Stefán Jökull Sigurðarson

Stefán Jökull Sigurðarson

Hi friends.

There are a lot of cool new features in C# 8 and one of my favorites is the new Null coalescing assignment (or compound assignment, whichever you prefer) operator. If you have ever written code like this:

You can simplify this code A LOT!

That is the new ??= operator in action, which takes care of doing the null check and assignment for you in one sweet syntactic sugar-rush! I also find it more readable, but some people might disagree, and that fine. Just pick whatever you prefer :)

And the best part is that it actually compiles down to the same efficient code! Just take a look at this sharplab.io sample to see what I mean.

You might have solved this with a Lazy<string> or by using something like _someValue = _someValue ?? InitializeMyValue(); as well but that's still more code to write than the new operator and less efficient as well. The Lazy<T> approach has some overhead and the null-coalescing operator + assignment has the added inefficiency of always making the variable assignment even if there is no need to (you can take a closer look at the ASM part of the SharpLab example above) but there it is for reference:

Hope this helps! :)

Sign up for more like this.

  • Blogs by Topic

The .NET Tools Blog

Essential productivity kit for .NET developers

  • Guide Guide

Indices, Ranges, and Null-coalescing Assignments – A Look at New language features in C# 8

Matthias Koch

With every new C# version that is released, we try to cover what’s new in the programming language we all use daily ( C# 7 ,  C# 7.1, 7.2 and 7.3 ). Today looks like a great day to start covering what’s new and coming in C# 8.

In case you want to start playing with C# 8, both ReSharper 2019.1 EAP  and Rider 2019.1 EAP  come with initial support for it.

In this post, we will cover indices, ranges and null-coalescing assignment. In future posts, we will look at switch expressions, patterns, async streams and IAsyncEnumerable , nullable reference types and more. Keep an eye on our blog – we’ll span a whole range of C# 8!

In this series:

  • Indices, Ranges, and Null-coalescing Assignments
  • Switch Expressions and Pattern-Based Usings
  • Recursive Pattern Matching
  • Async Streams
  • Nullable Reference Types: Migrating a Codebase
  • Nullable Reference Types: Contexts and Attributes

How to get C# 8?

First of all, we will need the .NET Core 3.0 preview installed on our machine. For ReSharper, Visual Studio 2019 is also required.

Once installed, we can edit our project and update the language version to specify we want to make use of C# 8 (or preview ). In Rider, we can do this from the Project Properties dialog :

Project Properties dialog

The manual way would be to edit the .csproj file as follows:

When using ReSharper or Rider, there is also a quick-fix that helps us set the language version with an Alt+Enter when our code contains new language features:

Set language version quick-fix

Indices and Ranges

Working with arrays becomes more expressive with the new types and operators introduced for indices and ranges ( discussion ). Previously, when we had to address items based on their position to the end of an array, the resulting code has looked rather clumsy:

Also, when we had to slice an array given the start and end position, there was quite some ceremony involved , for instance to calculate the length, pre-initialize an array or falling back to:

The latter method using Array.Copy is roughly what the compiler will emit behind the scenes when using the new Index and Range types.

Use index from end expression

Pro tip: this quick-fix can be applied in bulk on the full solution.

Here, the hat operator ^ indicates that we’re referring to an item coming from the end. Similarly, the item before the last would be ^2 and so on. Want to take a guess what ^0 results in? Right, we would get an IndexOutOfRangeException . Likewise, negative numbers would result in an ArgumentOutOfRangeException . By the way, the ^1 expression is of the type Index and could easily be extracted into a dedicated variable. We can also create them programmatically, for instance by calling new Index(1, fromEnd: true) . Also, instances of int will implicitly convert to an Index .

Let’s get back to the example of slicing an array . For this, we can make use of the range operator .. :

Remove redundant range bounds

To avoid unnecessary copying and allocations, we might want to call array.AsSpan() before slicing our array with a range, as this will access the original array. Also, many of the existing framework APIs, like Substring or Slice , have been updated to work with Index and Range objects.

Null-Coalescing Assignment

The new null-coalescing assignment ( discussion ) 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 :

With the added C# 8 support, ReSharper and Rider will tell us how our code can be written more elegantly:

Fix to compound assignment

The To Compound Assignment context action also works with other relevant operators as with + , - , * , / , and more.

Download ReSharper Ultimate 2019.1 EAP  or check out  Rider 2019.1 EAP  to start taking advantage of ReSharper’s language support updates and C# 8. We’d love to hear your thoughts!

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

null compound assignment c#

Collection Expressions – Using C# 12 in Rider and ReSharper

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 Const…

Matthias Koch

Generate Unit Tests Using AI Assistant

Can you make your life easier as a developer by using AI to generate unit tests? AI can provide a bit of automation to this daily development activity and make our development workflow a bit smoother if we use it thoughtfully. So in this blog post, we’ll take a look at using the JetBrains AI Assista…

Rachel Appel

Boost Code Quality with Qodana and GitHub Actions

It’s been roughly half a year since we introduced Qodana to .NET in our blog post about how to elevate your C# code quality with Qodana. Since then, we’ve been quite busy! Qodana went out of preview and into GA. Furthermore, we greatly improved the integration with our IDEs, providing an effortless …

Critical Thinking in an AI-Powered World

Critical Thinking in an AI-Powered World

Critical thinking techniques for use with JetBrains AI Assistant.

DEV Community

DEV Community

Mauro Petrini 👨‍💻

Posted on Sep 23, 2019 • Updated on Apr 26, 2020

The null-coalescing operator in C# 8.0

Welcome! Spanish articles on LinkedIn . You can follow me on Twitter for news.

What is null-coalescing?

According to ms docs, the null-coalescing operator ?? returns the value of its left-hand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator does not evaluate its right-hand operand if the left-hand operand evaluates to non-null.

Through a Youtube video, I'll show how to use the null coalescing operator in C# 8.0 and the evolution of this:

  • Finally with C# 8.0

We have a variable called age with a null value

We need to check if the value is null and then assign the value

We use the null coalescing operator

We use the compound assignment operator

For more information:

Youtube video

Github GIST

Top comments (1).

pic

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

peledzohar profile image

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

Nitpicking: The null coalescing operator ( ?? ) was around in c# 6 as well, and if memory serves, perhaps even also in c# 5. The null-coalescing assignment operator ( ??= ) is new, though.

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

tkarropoulos profile image

Mastering Resource Management in C# with the Disposable Pattern

Theodore Karropoulos - Feb 12

shegzee profile image

Creating Stunning Charts for Your ASP.NET Applications

S. Olusegun Ojo - Feb 12

vhugogarcia profile image

.NET MAUI: Update NuGet Packages using Visual Studio Code

Victor Hugo Garcia - Jan 29

homolibere profile image

C# Writing High-Performance Apps Using Span<T>;

Nick - Jan 29

DEV Community

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

  • PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

C# operator

last modified July 5, 2023

In this article we cover C# operators.

Expressions are constructed from operands and operators. The operators of an expression indicate which operations to apply to the operands. The order of evaluation of operators in an expression is determined by the precedence and associativity of the operators.

An operator is a special symbol which indicates a certain process is carried out. Operators in programming languages are taken from mathematics. Programmers work with data. The operators are used to process data. An operand is one of the inputs (arguments) of an operator.

C# operator list

The following table shows a set of operators used in the C# language.

An operator usually has one or two operands. Those operators that work with only one operand are called unary operators . Those who work with two operands are called binary operators . There is also one ternary operator ?: , which works with three operands.

Certain operators may be used in different contexts. For example the + operator. From the above table we can see that it is used in different cases. It adds numbers, concatenates strings or delegates; indicates the sign of a number. We say that the operator is overloaded .

C# unary operators

C# unary operators include: +, -, ++, --, cast operator (), and negation !.

C# sign operators

There are two sign operators: + and - . They are used to indicate or change the sign of a value.

The + and - signs indicate the sign of a value. The plus sign can be used to indicate that we have a positive number. It can be omitted and it is mostly done so.

The minus sign changes the sign of a value.

C# increment and decrement operators

Incrementing or decrementing a value by one is a common task in programming. C# has two convenient operators for this: ++ and -- .

The above two pairs of expressions do the same.

In the above example, we demonstrate the usage of both operators.

We initiate the x variable to 6. Then we increment x two times. Now the variable equals to 8.

We use the decrement operator. Now the variable equals to 7.

C# explicit cast operator

The explicit cast operator () can be used to cast a type to another type. Note that this operator works only on certain types.

In the example, we explicitly cast a float type to int .

Negation operator

The negation operator (!) reverses the meaning of its operand.

In the example, we build a negative condition: it is executed if the inverse of the expression is valid.

C# assignment operator

The assignment operator = assigns a value to a variable. A variable is a placeholder for a value. In mathematics, the = operator has a different meaning. In an equation, the = operator is an equality operator. The left side of the equation is equal to the right one.

Here we assign a number to the x variable.

The previous expression does not make sense in mathematics. But it is legal in programming. The expression adds 1 to the x variable. The right side is equal to 2 and 2 is assigned to x .

This code example results in syntax error. We cannot assign a value to a literal.

C# concatenating strings

The + operator is also used to concatenate strings.

We join three strings together using string concatenation operator.

C# arithmetic operators

The following is a table of arithmetic operators in C#.

The following example shows arithmetic operations.

In the preceding example, we use addition, subtraction, multiplication, division, and remainder operations. This is all familiar from the mathematics.

The % operator is called the remainder or the modulo operator. It finds the remainder of division of one number by another. For example, 9 % 4 , 9 modulo 4 is 1, because 4 goes into 9 twice with a remainder of 1.

Next we show the distinction between integer and floating point division.

In the preceding example, we divide two numbers.

In this code, we have done integer division. The returned value of the division operation is an integer. When we divide two integers the result is an integer.

If one of the values is a double or a float, we perform a floating point division. In our case, the second operand is a double so the result is a double.

C# Boolean operators

In C#, we have three logical operators. The bool keyword is used to declare a Boolean value.

Boolean operators are also called logical.

Many expressions result in a boolean value. Boolean values are used in conditional statements.

Relational operators always result in a boolean value. These two lines print false and true.

The body of the if statement is executed only if the condition inside the parentheses is met. The y > x returns true, so the message "y is greater than x" is printed to the terminal.

The true and false keywords represent boolean literals in C#.

Example shows the logical and operator. It evaluates to true only if both operands are true.

Only one expression results in True .

The logical or || operator evaluates to true, if either of the operands is true.

If one of the sides of the operator is true, the outcome of the operation is true.

Three of four expressions result in true.

The negation operator ! makes true false and false true.

The example shows the negation operator in action.

The || , and && operators are short circuit evaluated. Short circuit evaluation means that the second argument is only evaluated if the first argument does not suffice to determine the value of the expression: when the first argument of the logical and evaluates to false, the overall value must be false; and when the first argument of logical or evaluates to true, the overall value must be true. Short circuit evaluation is used mainly to improve performance.

An example may clarify this a bit more.

We have two methods in the example. They are used as operands in boolean expressions.

The One method returns false . The short circuit && does not evaluate the second method. It is not necessary. Once an operand is false , the result of the logical conclusion is always false . Only "Inside one" is only printed to the console.

In the second case, we use the || operator and use the Two method as the first operand. In this case, "Inside two" and "Pass" strings are printed to the terminal. It is again not necessary to evaluate the second operand, since once the first operand evaluates to true , the logical or is always true .

C# relational operators

Relational operators are used to compare values. These operators always result in boolean value.

Relational operators are also called comparison operators.

In the code example, we have four expressions. These expressions compare integer values. The result of each of the expressions is either true or false. In C# we use == to compare numbers. Some languages like Ada, Visual Basic, or Pascal use = for comparing numbers.

C# bitwise operators

Decimal numbers are natural to humans. Binary numbers are native to computers. Binary, octal, decimal, or hexadecimal symbols are only notations of the same number. Bitwise operators work with bits of a binary number. Bitwise operators are seldom used in higher level languages like C#.

The bitwise negation operator changes each 1 to 0 and 0 to 1.

The operator reverts all bits of a number 7. One of the bits also determines, whether the number is negative or not. If we negate all the bits one more time, we get number 7 again.

The bitwise and operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 only if both corresponding bits in the operands are 1.

The first number is a binary notation of 6, the second is 3, and the result is 2.

The bitwise or operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 if either of the corresponding bits in the operands is 1.

The result is 00110 or decimal 7.

The bitwise exclusive or operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 if one or the other (but not both) of the corresponding bits in the operands is 1.

The result is 00101 or decimal 5.

C# compound assignment operators

The compound assignment operators consist of two operators. They are shorthand operators.

The += compound operator is one of these shorthand operators. The above two expressions are equal. Value 3 is added to the a variable.

Other compound operators are:

In the example, we use two compound operators.

The a variable is initiated to one. 1 is added to the variable using the non-shorthand notation.

Using a += compound operator, we add 5 to the a variable. The statement is equal to a = a + 5; .

Using the *= operator, the a is multiplied by 3. The statement is equal to a = a * 3; .

C# new operator

The new operator is used to create objects and invoke constructors.

In the example, we create a new custom object and a array of integers utilizing the new operator.

This is a constructor. It is called at the time of the object creation.

C# access operator

The access operator [] is used with arrays, indexers, and attributes.

In the example, we use the [] operator to get an element of an array, value of a dictionary pair, and activate a built-in attribute.

We define an array of integers. We get the first element with vals[0] .

A dictionary is created. With domains["de"] , we get the value of the pair that has the "de" key.

We active the built-in Obsolete attribute. The attribute issues a warning.

When we run the program, it produces the warning: warning CS0618: 'oldMethod()' is obsolete: 'Don't use OldMethod, use NewMethod instead' .

C# index from end operator ^

The index from end operator ^ indicates the element position from the end of a sequence. For instance, ^1 points to the last element of a sequence and ^n points to the element with offset length - n .

In the example, we apply the operator on an array and a string.

We print the last and the last but one element of the array.

We print the last letter of the word.

C# range operator ..

The .. operator specifies the start and end of a range of indices as its operands. The left-hand operand is an inclusive start of a range. The right-hand operand is an exclusive end of a range.

Operands of the .. operator can be omitted to get an open-ended range.

In the example, we use the .. operator to get array slices.

We create an array slice from index 1 till index 4; the last index 4 is not included.

Here we esentially create a copy of the array.

C# type information

Now we concern ourselves with operators that work with types.

The sizeof operator is used to obtain the size in bytes for a value type. The typeof is used to obtain the System.Type object for a type.

We use the sizeof and typeof operators.

We can see that the int type is an alias for System.Int32 and the float is an alias for the System.Single type.

The is operator checks if an object is compatible with a given type.

We create two objects from user defined types.

We have a Base and a Derived class. The Derived class inherits from the Base class.

Base equals Base and so the first line prints True. The Base is also compatible with Object type. This is because each class inherits from the mother of all classes — the Object class.

The derived object is compatible with the Base class because it explicitly inherits from the Base class. On the other hand, the _base object has nothing to do with the Derived class.

The as operator is used to perform conversions between compatible reference types. When the conversion is not possible, the operator returns null. Unlike the cast operation which raises an exception.

In the above example, we use the as operator to perform casting.

We try to cast various types to the string type. But only once the casting is valid.

C# operator precedence

The operator precedence tells us which operators are evaluated first. The precedence level is necessary to avoid ambiguity in expressions.

What is the outcome of the following expression, 28 or 40?

Like in mathematics, the multiplication operator has a higher precedence than addition operator. So the outcome is 28.

To change the order of evaluation, we can use parentheses. Expressions inside parentheses are always evaluated first.

The following table shows common C# operators ordered by precedence (highest precedence first):

Operators on the same row of the table have the same precedence.

In this code example, we show a few expressions. The outcome of each expression is dependent on the precedence level.

This line prints 28. The multiplication operator has a higher precedence than addition. First, the product of 5*5 is calculated, then 3 is added.

In this case, the negation operator has a higher precedence. First, the first true value is negated to false, then the | operator combines false and true, which gives true in the end.

C# associativity rule

Sometimes the precedence is not satisfactory to determine the outcome of an expression. There is another rule called associativity . The associativity of operators determines the order of evaluation of operators with the same precedence level.

What is the outcome of this expression, 9 or 1? The multiplication, deletion and the modulo operator are left to right associated. So the expression is evaluated this way: (9 / 3) * 3 and the result is 9.

Arithmetic, boolean, relational, and bitwise operators are all left to right associated.

On the other hand, the assignment operator is right associated.

In the example, we have two cases where the associativity rule determines the expression.

The assignment operator is right to left associated. If the associativity was left to right, the previous expression would not be possible.

The compound assignment operators are right to left associated. We might expect the result to be 1. But the actual result is 0. Because of the associativity. The expression on the right is evaluated first and than the compound assignment operator is applied.

C# null-conditional operator

A null-conditional operator applies a member access, ?. , or element access, ?[] , operation to its operand only if that operand evaluates to non-null. If the operand evaluates to null , the result of applying the operator is null.

In the example, we have a User class with two members: Name and Occupation . We access the name member of the objects with the help of the ?. operator.

We have a list of users. One of them is initialized with null values.

We use the ?. to access the Name member and call the ToUpper method. The ?. prevents the System.NullReferenceException by not calling the ToUpper on the null value.

In the following example, we use the ?[] operator. The operator allows to place null values into a collection.

In this example, we have a null value in an array. We prevent the System.NullReferenceException by applying the ?. operator on the array elements.

C# null-coalescing operator

The null-coalescing operator ?? is used to define a default value for a nullable type. It returns the left-hand operand if it is not null; otherwise it returns the right operand. When we work with databases, we often deal with absent values. These values come as nulls to the program. This operator is a convenient way to deal with such situations.

An example program for null-coalescing operator.

Two nullable int types are initiated to null . The int? is a shorthand for Nullable<int> . It allows to have null values assigned to int types.

We want to assign a value to z variable. But it must not be null . This is our requirement. We can easily use the null-coalescing operator for that. In case both x and y variables are null, we assign -1 to z .

C# null-coalescing assignment operator

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 does not evaluate its right-hand operand if the left-hand operand evaluates to non-null. It is available in C# 8.0 and later.

In the example, we use the null-coalescing assignment operator on a list of integer values.

First, the list is assigned to null .

We use the ??= to assign a new list object to the variable. Since it is null , the list is assigned.

We add some values to the list and print its contents.

We try to assign a new list object to the variable. Since the variable is not null anymore, the list is not assigned.

C# ternary operator

The ternary operator ?: is a conditional operator. It is a convenient operator for cases where we want to pick up one of two values, depending on the conditional expression.

If cond-exp is true, exp1 is evaluated and the result is returned. If the cond-exp is false, exp2 is evaluated and its result is returned.

In most countries the adulthood is based on your age. You are adult if you are older than a certain age. This is a situation for a ternary operator.

First the expression on the right side of the assignment operator is evaluated. The first phase of the ternary operator is the condition expression evaluation. So if the age is greater or equal to 18, the value following the ? character is returned. If not, the value following the : character is returned. The returned value is then assigned to the adult variable.

A 31 years old person is adult.

C# Lambda operator

The => token is called the lambda operator. It is an operator taken from functional languages. This operator can make the code shorter and cleaner. On the other hand, understanding the syntax may be tricky. Especially if a programmer never used a functional language before.

Wherever we can use a delegate, we also can use a lambda expression. A definition for a lambda expression is: a lambda expression is an anonymous function that can contain expressions and statements. On the left side we have a group of data and on the right side an expression or a block of statements. These statements are applied on each item of the data.

In lambda expressions we do not have a return keyword. The last statement is automatically returned. And we do not need to specify types for our parameters. The compiler will guess the correct parameter type. This is called type inference.

We have a list of integer numbers. We print all numbers that are greater than 3.

We have a generic list of integers.

Here we use the lambda operator. The FindAll method takes a predicate as a parameter. A predicate is a special kind of a delegate that returns a boolean value. The predicate is applied for all items of the list. The val is an input parameter specified without a type. We could explicitly specify the type but it is not necessary.

The compiler will expect an int type. The val is a current input value from the list. It is compared if it is greater than 3 and a boolean true or false is returned. Finally, the FindAll will return all values that met the condition. They are assigned to the sublist collection.

The items of the sublist collection are printed to the terminal.

Values from the list of integers that are greater than 3.

This is the same example. We use a anonymous delegate instead of a lambda expression.

C# calculating prime numbers

We are going to calculate prime numbers.

In the above example, we deal with many various operators. A prime number (or a prime) is a natural number that has exactly two distinct natural number divisors: 1 and itself. We pick up a number and divide it by numbers, from 1 up to the picked up number. Actually, we do not have to try all smaller numbers; we can divide by numbers up to the square root of the chosen number. The formula will work. We use the remainder division operator.

We calculate primes from these numbers.

By definition, 1 is not a prime

We skip the calculations for 2 and 3: they are primes. Note the usage of the equality and conditional or operators. The == has a higher precedence than the || operator. So we do not need to use parentheses.

We are OK if we only try numbers smaller than the square root of a number in question. It was mathematically proven that it is sufficient to take into account values up to the square root of the number in question.

This is a while loop. The i is the calculated square root of the number. We use the decrement operator to decrease the i by one each loop cycle. When the i is smaller than 1, we terminate the loop. For example, we have number 9. The square root of 9 is 3. We divide the 9 number by 3 and 2.

This is the core of the algorithm. If the remainder division operator returns 0 for any of the i values then the number in question is not a prime.

C# operators and expressions

In this article we covered C# operators.

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all C# tutorials .

IMAGES

  1. Compound Assignment Operators in C Programming Language

    null compound assignment c#

  2. Exploring Compound Assignment Operators in C

    null compound assignment c#

  3. Video 16 C++ statements (Null & compound Statement) And flow (Execution

    null compound assignment c#

  4. PPT

    null compound assignment c#

  5. Coalescing operator and Compound assignment operator in C#

    null compound assignment c#

  6. Compound Assignment Operator in C++

    null compound assignment c#

VIDEO

  1. Модуль 38. Null и типы Nullable в языке программирования C#

  2. Lesson16 Compound assignment with Arithmetic Operators & Assignment By Reference

  3. Lecture 1 of JS (Introduction of JS, variables, and datatypes)

  4. Understanding ??= Null Coalescing Assignment Operator

  5. Compound Assignment Operators in C++ || C++ Programming #viral #subscribe

  6. Dynamic Dispatch

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

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

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

    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.

  6. Coalescing operator and Compound assignment operator in C#

    First, a null coalescing operator (??) is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null, otherwise, it returns the right operand. So it's mainly used to simplify checking for null values and also assign a default value to a variable when the value is null.

  7. C# 8

    There are a lot of cool new features in C# 8 and one of my favorites is the new Null coalescing assignment (or compound assignment, whichever you prefer) operator. If you have ever written code like this: private string _someValue; public string SomeMethod() { // Let's do an old-school null check and initialize if needed.

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

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

  10. The null-coalescing operator in C# 8.0

    What is null-coalescing? According to ms docs, the null-coalescing operator ?? returns the value of its left-hand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator does not evaluate its right-hand operand if the left-hand operand evaluates to non-null. Through a Youtube video, I'll show how ...

  11. c#

    myFactory.GetNextObject().MyProperty += 5; You _certainly wouldn't do. myFactory.GetNextObject().MyProperty = myFactory.GetNextObject().MyProperty + 5; You could again use a temp variable, but the compound assignment operator is obviously more succinct. Granted, these are edge cases, but it's not a bad habit to get into.

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

  13. Null-Coalescing assignment C# 8.0

    The null coalescing operator was introduced in C# 7.0. ... As the "nums" variable value is null during the first assignment, the value of the right-hand operand is assigned to variable ...

  14. Why are there no ||= or &&= operators in C#?

    The first one evaluates as: a = b != null ? b : c; The second one - is what you are asking: a = a != null ? a : b; Sure, at the place of any of these vars might be complex expressions. Here is a reference: null-coalescing operators

  15. Null-coalescing assignment operator in C# 8.0

    In this series we will discuss the new features in C# 8.0In this video we will learn Null-coalescing assignment operator which is one of the new feature in C...

  16. C# operator

    The compound assignment operators are right to left associated. We might expect the result to be 1. But the actual result is 0. Because of the associativity. The expression on the right is evaluated first and than the compound assignment operator is applied. $ dotnet run 0 0 0 0 0 C# null-conditional operator

  17. c#

    I tried to use an extension method but extension methods don't allow the use of the ref or out keywords as the first parameter. I can't seem to find any built in operator that does this. The point is to avoid the assignment because the obj 's propertyset property is set to true no matter what it is being set to null or otherwise. meaning obj ...

  18. Check for null and assign to a variable at once in C# 8

    set => myBackingField = value; } The value for backing field will be instantiated on first call of the Property getter. Thus, the value of the MyProperty will never be null. 3 operations at once: check for null. conditionally assign fall back value. and return (or use) the result. edited Jul 11, 2020 at 16:23.