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:
| Cách | Giá trị | IsNullOrEmpty | IsNullOrWhiteSpace |
|---|---|---|---|
| null | null | true | true |
| "" | Empty | true | true |
| string.Empty | Empty | true | true |
| " " | Space | false | true |