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

CsharpProgrammingServer Side Programming

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!
raja
Published on 31-Aug-2018 12:12:56
Advertisements