เมธอด String.IsNullOrWhiteSpace() ใน C# ใช้ตรวจสอบว่าสตริงที่ระบุเป็น null, ว่าง (""), หรือประกอบด้วย whitespace เท่านั้น (space, tab, newline, carriage return, ฯลฯ)
ไวยากรณ์ (Syntax)
public static bool IsNullOrWhiteSpace(string value);
- value — สตริงที่ต้องการทดสอบ
- คืนค่า
trueหาก null, empty, หรือ whitespace-only, มิฉะนั้นfalse
ตัวอย่างที่ 1: null และ Empty String
using System;
public class Demo
{
public static void Main()
{
string str1 = null;
string str2 = String.Empty;
Console.WriteLine("Is string1 null or whitespace? = " + String.IsNullOrWhiteSpace(str1));
Console.WriteLine("Is string2 null or whitespace? = " + String.IsNullOrWhiteSpace(str2));
}
}
ผลลัพธ์
Is string1 null or whitespace? = True Is string2 null or whitespace? = True
ตัวอย่างที่ 2: Whitespace characters และสตริงปกติ
using System;
public class Demo
{
public static void Main()
{
string str1 = "\n"; // newline
string str2 = "Tim"; // สตริงปกติ
Console.WriteLine("Is string1 null or whitespace? = " + String.IsNullOrWhiteSpace(str1));
Console.WriteLine("Is string2 null or whitespace? = " + String.IsNullOrWhiteSpace(str2));
}
}
ผลลัพธ์
Is string1 null or whitespace? = True Is string2 null or whitespace? = False
สรุป
IsNullOrWhiteSpace()=IsNullOrEmpty()+ ตรวจสอบ whitespace-only- Whitespace characters รวม: space (' '), tab ('\t'), newline ('\n'), carriage return ('\r'), vertical tab ('\v'), form feed ('\f'), และ Unicode whitespace อื่นๆ
- ใช้สำหรับ validation input — ตรวจสอบว่าผู้ใช้กรอกข้อมูลจริงหรือแค่เว้นวรรค
- เร็วกว่า
str == null || str.Trim() == ""เพราะไม่สร้างสตริงใหม่ - เมธอดเก่า:
String.IsNullOrEmpty(str)— ตรวจสอบแค่ null หรือ "" (ไม่นับ whitespace)
ตารางเปรียบเทียบ
| ค่าสตริง | IsNullOrEmpty | IsNullOrWhiteSpace |
|---|---|---|
| null | true | true |
| "" (empty) | true | true |
| " " | false | true |
| "\t\n\r" | false | true |
| " hello " | false | false |
| "hello" | false | false |
ตัวอย่างใช้งานจริง: Input Validation
public void RegisterUser(string username, string email)
{
if (string.IsNullOrWhiteSpace(username))
throw new ArgumentException("Username cannot be empty or whitespace", nameof(username));
if (string.IsNullOrWhiteSpace(email))
throw new ArgumentException("Email cannot be empty or whitespace", nameof(email));
// ... บันทึกข้อมูล
}