Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Khởi tạo chuỗi rỗng trong C#

Cách 1: Gán null

string myStr = null;
if (string.IsNullOrEmpty(myStr))
    Console.WriteLine("Chuỗi rỗng hoặc null!");

Cách 2: string.Empty (khuyến nghị)

string myStr = string.Empty;
if (string.IsNullOrEmpty(myStr))
    Console.WriteLine("Chuỗi rỗng hoặc null!");

Ví dụ đầy đủ

using System;

namespace Demo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string myStr = string.Empty;
            
            if (string.IsNullOrEmpty(myStr))
                Console.WriteLine("Chuỗi rỗng hoặc null!");
            else
                Console.WriteLine("Chuỗi không rỗng!");
        }
    }
}

Kết quả

Chuỗi rỗng hoặc null!

So sánh:

string.Empty là const, không allocate mới, hiệu năng tốt hơn "" (dù compiler optimize "" thành Empty).

CáchGiá trịIsNullOrEmptyIsNullOrWhiteSpace
nullnulltruetrue
""Emptytruetrue
string.EmptyEmptytruetrue
" "Spacefalsetrue