How to use null-coalescing operator?

Total Post:214

 956  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