How to use null-coalescing operator?

Total Post:214

Points:1642
C# 
C#
 817  View(s)
Ratings:
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

    Points:135
    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");
                Console.WriteLine(i);
                Console.ReadKey();
            }
        }
    }
     

      Modified On Apr-11-2018 11:04:56 PM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!