Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
Object and Collection Initializer in C#
Next article icon

Null-Coalescing Assignment Operator in C# 8.0

Last Updated : 11 Dec, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Syntax:

p ??= q

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.
  • You are allowed to use ??= operator with reference types and value types.

    Example:




    // C# program to illustrate how to use 
    // ??= operator with value types and 
    // reference types
    using System;
       
    namespace example {
       
    class GFG {
       
        static void Main(string[] args)
        {
       
            // Reference types
            string item_1 = null;
            string item_2 = null;
            string item_4 = "GeeksforGeeks";
            string item_5 = "GFG";
       
            // Using ??= operator
            item_1 = item_1 ??= item_4;
            string item_6 = item_2 ??= item_5;
       
            Console.WriteLine("Value of item_1 is: {0}\n"+
               "Value of item_6 is:{1}", item_1, item_6);
       
            // Value types
            int ? ele_1 = null;
       
            GFG obj = new GFG();
       
            // Using ??= operator assigns
            // the value of ele_1
            // And also you are allowed to 
            // use method with ??= operator
            ele_1 = ele_1 ??= obj.Add(10, 30);
            Console.WriteLine("Value of ele_1 is {0}", ele_1);
        }
       
        // Method
        public int Add(int a, int b)
        {
            int result = a + b;
            return result;
        }
    }
    }
     
     

    Output:

      Value of item_1 is: GeeksforGeeks  Value of item_6 is:GFG  Value of ele_1 is 40  
  • With the help of ??= operator you can remove many redundant “if-else” conditions and make your code more compact and readable. As shown in the below example:

    Example:




    // C# program to illustrate how to use
    // ??= operator to remove if statements
    using System;
       
    namespace example {
       
    class GFG {
          
        // Main Method
        static void Main(string[] args)
        {
            // Nullable variable
            int ? element = null;
       
            // Checking the element is null or not
            if (element is null) {
                  
                // Assign a new value to the element
                // Using ??= operator
                int ? new_element = element ??= 400;
                Console.WriteLine("Element is null. "+
                 "So the new element is: {0}", new_element);
            }
        }
    }
    }
     
     

    Output:

      Element is null. So the new element is: 400  




    // C# program to illustrate how to use
    // ??= operator to remove if statements
    using System;
       
    namespace example {
       
    class Program {
        static void Main(string[] args)
        {
            // Nullable variable
            int ? element = null;
       
            // Using ??= operator
            // Assign values to the null variable
            element ??= 400;
            Console.WriteLine("Element is: {0}", element);
        }
    }
    }
     
     

    Output:

    Element is: 400
  • You can also use ??= operator like a nested chain. It makes your code more readable.

    Example:




    // C# program to illustrate 
    // how to nest ??= operator
    using System;
       
    namespace example {
       
    class GFG {
          
        // Main Method
        static void Main(string[] args)
        {
            // Nullable variables
            int ? ele1 = null;
            int ? ele2 = null;
            int ? ele3 = 45;
       
            // Using Nested ??= operator
            int ? result = ele1 ??= ele2 ??= ele3;
              
            Console.WriteLine("Element is: {0}", result);
        }
    }
    }
     
     

    Output:

    Element is: 45


Next Article
Object and Collection Initializer in C#
author
ankita_saini
Improve
Article Tags :
  • C#
  • CSharp-8.0

Similar Reads

  • Null-Coalescing Operator in C#
    In C#, ?? operator is known as Null-coalescing operator. It will return the value of its left-hand operand if it is not null. If it is null, then it will evaluate the right-hand operand and returns its result. Or if the left-hand operand evaluates to non-null, then it does not evaluate its right-han
    4 min read
  • Object and Collection Initializer in C#
    An object and collection initializer is an interesting and very useful feature of C# language. This feature provides a different way to initialize an object of a class or a collection. This feature is introduced in C# 3.0 or above. The main advantages of using these are to makes your code more reada
    3 min read
  • LINQ | Concatenation Operator | Concat
    The concatenation is a process in which one sequence is appended into another sequence. In LINQ, the concatenation operation contains only one operator that is known as Concat. It is used to append two same types of sequences or collections and return a new sequence or collection. It does not suppor
    3 min read
  • LINQ | Element Operator | ElementAt
    The element operators are used to return a single, or a specific element from the sequence or collection. For example, in a school when we ask, who is the principal? Then there will be only one person that will be the principal of the school. So the number of students is a collection and the princip
    3 min read
  • Is vs As operator keyword in C#
    The difference between is and as operators are as follows: The is operator is used to check if the run-time type of an object is compatible with the given type or not whereas as operator is used to perform conversion between compatible reference types or Nullable types. The is operator is of boolean
    3 min read
  • LINQ | Element Operator | FirstOrDefault
    The element operators are used to return a single, or a specific element from the sequence or collection. For example, in a school when we ask, who is the principal? Then there will be only one person that will be the principal of the school. So the number of students is a collection and the princip
    4 min read
  • Uri.Equality() Operator in C# with Examples
    Uri.Equality() Operator is used to compare two Uri objects. If two Uri objects contain the same Uri, then it returns the true otherwise it returns false. Syntax: public static bool operator == (Uri uri1, Uri uri2); Parameter: This method has the following parameters: uri1: This parameter is the firs
    2 min read
  • LINQ | Grouping Operator | GroupBy
    In LINQ, grouping operators pick the elements of the sequence or collection which contains common attributes and serve them in a group. Or in other words, we can say that the grouping operator returns the group of elements based on the given key. This group is held in a special type of collection, w
    5 min read
  • Range and Indices in C# 8.0
    Range and Indices introduced in C# 8.0. released as part of .NET Core 3.0 and .NET Framework 4.8 they provide a short syntax to represent or access a single or a range of elements from the given sequence or collections. System.Index: It represents an index in the given sequence or collection.System.
    4 min read
  • LINQ | Generation Operator | DefaultIfEmpty
    The generation operators are used for creating a new sequence of values. The Standard Query Operator supports 4 different types of generation operators: DefaultIfEmpty Empty Range Repeat DefaultIfEmpty Operator The DefaultIfEmpty operator is used to replace an empty collection or sequence with a def
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences