Gán chuỗi rỗng:
string myStr = string.Empty;
Kiểm tra null hoặc rỗng:
if (string.IsNullOrEmpty(myStr))
{
Console.WriteLine("Chuỗi rỗng hoặc null!");
}
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("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!
Lưu ý:
string.Empty=""(hằng số, không allocate mới)String.Emptytương tự (alias của System.String)IsNullOrEmptykiểm tra cả null và ""IsNullOrWhiteSpacethêm kiểm tra khoảng trắng