.Net:- Operator – The null-coalescing operator ??

Background

.Net Console.WriteLine is null safe.

But, then some functions may not be.

To protect yourself in the case of nullable variables, please consider the use of the ?? operator.

 

Code

 


using System;

class HelloWorld 
{
    
  static void Main() 
  {
      contactList();
  }
  
  static void contactList()
  {
      string friendMale;
      string friendFemale;
      string neighbor;
      string gender;
      string genderUnknown = "Unknown";
      
      friendMale = "sampson";
      Console.WriteLine
         (
             "Friend {0} is a {1}"
             , friendMale
             , "Male"
         );
      
      friendFemale = "delilah";
      Console.WriteLine
         (
               "Friend {0} is {1}"
             , friendFemale
             , "Female"
        );   
      
      neighbor = "Sallie";
      gender = null;

      // traditional
      Console.WriteLine
      (
            "Friend {0} is {1}"
          , neighbor
          , gender
      );    
      
      //Long Form
      if (gender == null)
      {
          
          Console.WriteLine
          (
                "Friend {0} is {1}"
              , neighbor
              , genderUnknown
          ); 
          
      }
      else
      {
          
          Console.WriteLine
          (
                "Friend {0} is {1}"
              , neighbor
              , gender
          ); 
          
      }
      
      //short form
      //use operator ??
      Console.WriteLine
        (
                "Friend {0} is {1}"
                , neighbor
                , gender ?? genderUnknown
        ); 
        
  } //method
  
} // class

Output

Image

Textual

Friend sampson is a Male
Friend delilah is Female
Friend Sallie is
Friend Sallie is Unknown
Friend Sallie is Unknown

References

  1. Microsoft
    • Learn > .NET > C# guide > Language reference > Operators and expressions
      • ?? and ??= operators (C# reference)
        Link

One thought on “.Net:- Operator – The null-coalescing operator ??

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s