Computer >> Máy Tính >  >> Lập trình >> C#

Làm thế nào để sử dụng string.Empty hoặc String.Empty để khởi tạo một chuỗi trong C #?

Đặt chuỗi là trống bằng cách sử dụng string.Empty trong C # -

string myStr = string.Empty;

Để kiểm tra xem nó có phải là một chuỗi hay không, hãy sử dụng phương thức IsNullOrEmpty () -

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

Sau đây là một ví dụ -

Ví dụ

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!");
         }
      }
   }
}

Đầu ra

String is empty or null!