Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอด IsNullOrWhiteSpace() ใน C#

เมธอด string.IsNullOrWhiteSpace() เป็นวิธีสะดวกในการตรวจสอบว่าสตริงเป็น null, ว่างเปล่า หรือประกอบด้วยอักขระ whitespace เท่านั้น คืนค่า bool

ตัวอย่างการตรวจสอบ

bool val1 = string.IsNullOrWhiteSpace(null);  // true
bool val2 = string.IsNullOrWhiteSpace(" ");   // true
bool val3 = string.IsNullOrWhiteSpace("5");   // false

ตัวอย่างโค้ดเต็ม

using System;

public class Demo
{
    public static void Main()
    {
        bool val1 = string.IsNullOrWhiteSpace(null);
        bool val2 = string.IsNullOrWhiteSpace(" ");
        bool val3 = string.IsNullOrWhiteSpace("5");
        Console.WriteLine(val1); // True
        Console.WriteLine(val2); // True
        Console.WriteLine(val3); // False
    }
}

ผลลัพธ์

True
True
False

กรณีใช้งานทั่วไป: ตรวจสอบข้อมูลนำเข้าจากผู้ใช้ ก่อนบันทึกลงฐานข้อมูลหรือประมวลผลต่อ