How to use null-coalescing operator?

Total Post:214

 1343  View(s)
Rate this:

How to use ?? null-coalescing operator in c# . I have never used ?? operator. And  How we can assign default value when it is null using ?? Operator.

Please help 
  1. Post:19

    Re: How to use null-coalescing operator?

    The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise, it returns the right hand operand.


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    namespace ConsoleApplication1
        class Program
            static int? GetNullableInt()
                return null;
            static string GetStringValue()
                return "Mindstick Softwares";
            static void Main()
                            int? x = null;
                // Set y to the value of x if x is NOT null; otherwise,
                // if x = null, set y to 5.
                int y = x ?? 5;
                // Assign i to return value of the method if the method's result
                // is NOT null; otherwise, if the result is null, set i to the
                // default value of int.
                int i = GetNullableInt() ?? default(int);
                string m = GetStringValue();
                // Display the value of s if s is NOT null; otherwise,
                // display the string "Unspecified".
                Console.WriteLine(m?? "Unspecified");

      Modified On Apr-11-2018 11:04:56 PM
  1. Post:2

    Re: How to use null-coalescing operator?

    The ?? operator is called the null-coalescing operator. You can use it to provide a default value for nullable value types or for reference types. The operator returns the left value if it’s not null; otherwise, the right operand. Here is an example of using the operator.

    int? x = null;
    int y = x ?? -1;

    In this case, the value of y is -1 because x is null. You can also nest the null-coalescing operator, below is an example,

    int? x = null;
    int? z = null;
    int y = x ??
            z ??

    Of course, you can achieve the same with an if statement but the null-coalescing operator can shorten your code and improve its readability.

    You can learn more about Null Coalescing Operator C# here.


Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.