How to initialize a string to an empty string in C#?


To initialize a string to an empty list −

string myStr = null;

Now, use the built-in method IsNullOrEmpty() to check whether the list is empty or not −

if (string.IsNullOrEmpty(myStr)) {
   Console.WriteLine("String is empty or null!");
}

Let us see the complete code −

Example

 Live Demo

using System;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         string myStr = null;

         if (string.IsNullOrEmpty(myStr)) {
            Console.WriteLine("String is empty or null!");
         }
         Console.ReadKey();
      }
   }
}

Output

String is empty or null!

Another way to initialize a string to an empty string, try the following code. Here, we have used string.Empty −

Example

 Live Demo

using System;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         string myStr = string.Empty;

         if (string.IsNullOrEmpty(myStr)) {
            Console.WriteLine("String is empty or null!");
         } else {
            Console.WriteLine("String isn't empty or null!");
         }
      }
   }
}

Output

String is empty or null!

Updated on: 22-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements