CSharp - String null and empty Value

Introduction

An empty string has a length of zero.

To create an empty string, you can use either a literal or the static string.Empty field.

To test for an empty string, you can either perform an equality comparison or test its Length property:

Demo

using System;
class MainClass{/*from ww w.  ja v a 2s.  c o m*/
   public static void Main(string[] args){
         string empty = "";
         Console.WriteLine (empty == "");              // True
         Console.WriteLine (empty == string.Empty);    // True
         Console.WriteLine (empty.Length == 0);        // True

   }
}

Result

Because strings are reference types, they can also be null:

Demo

using System;
class MainClass{/*from ww  w.java  2s.c o  m*/
   public static void Main(string[] args){
         string nullString = null;
         Console.WriteLine (nullString == null);        // True
         Console.WriteLine (nullString == "");          // False
         Console.WriteLine (nullString.Length == 0);    // NullReferenceException
   }
}

Result

static string.IsNullOrEmpty method tells whether a given string is either null or empty.

Exercise