Giới thiệu
Phương thức tĩnh String.IsNullOrWhiteSpace(string value) kiểm tra xem chuỗi có là null, rỗng (""), hoặc chỉ chứa ký tự khoảng trắng (space, tab, newline, v.v.) hay không. Trả về true nếu thỏa mãn một trong các điều kiện trên.
Cú pháp
public static bool IsNullOrWhiteSpace(string value);
Ví dụ 1 - Null và Empty
using System;
public class Demo
{
public static void Main()
{
string str1 = null;
string str2 = String.Empty;
Console.WriteLine("str1 null hoặc whitespace? = " + String.IsNullOrWhiteSpace(str1));
Console.WriteLine("str2 null hoặc whitespace? = " + String.IsNullOrWhiteSpace(str2));
}
}
Kết quả
str1 null hoặc whitespace? = True str2 null hoặc whitespace? = True
Ví dụ 2 - Whitespace và chuỗi thường
using System;
public class Demo
{
public static void Main()
{
string str1 = "\n"; // Chỉ chứa newline
string str2 = "Tim"; // Chuỗi bình thường
Console.WriteLine("str1 null hoặc whitespace? = " + String.IsNullOrWhiteSpace(str1));
Console.WriteLine("str2 null hoặc whitespace? = " + String.IsNullOrWhiteSpace(str2));
}
}
Kết quả
str1 null hoặc whitespace? = True str2 null hoặc whitespace? = False
So sánh với IsNullOrEmpty
string s1 = " "; // 3 space
string s2 = "\t\n"; // tab + newline
Console.WriteLine("IsNullOrEmpty(s1) = " + string.IsNullOrEmpty(s1)); // False
Console.WriteLine("IsNullOrWhiteSpace(s1) = " + string.IsNullOrWhiteSpace(s1)); // True
Console.WriteLine("IsNullOrEmpty(s2) = " + string.IsNullOrEmpty(s2)); // False
Console.WriteLine("IsNullOrWhiteSpace(s2) = " + string.IsNullOrWhiteSpace(s2)); // True
Lưu ý quan trọng
IsNullOrWhiteSpace=IsNullOrEmptyHOẶCTrim().Length == 0.- Ký tự whitespace theo Unicode: space (U+0020), tab (U+0009), newline (U+000A), carriage return (U+000D), và các ký tự separator khác.
- Hiệu suất:
IsNullOrWhiteSpacetối ưu hơn so vớistr == null || str.Trim() == "". - Dùng để validate input người dùng, config, file parsing.
- Trong .NET Core/.NET 5+, có overload
IsNullOrWhiteSpace(ReadOnlySpan<char>)tránh cấp phát chuỗi con.