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

เมธอด String.IsNullOrEmpty() ใน C# : ตรวจสอบสตริงว่างหรือ null

เมธอด String.IsNullOrEmpty() ใน C# ใช้ตรวจสอบว่าสตริงที่ระบุเป็น null หรือสตริงว่าง ("") หรือไม่ คืนค่า true หากเป็น null หรือว่าง มิฉะนั้นคืน false

รูปแบบไวยากรณ์ (Syntax)

public static bool IsNullOrEmpty(string val);

val : สตริงที่ต้องการทดสอบ

ตัวอย่างที่ 1: สตริงปกติและสตริงที่มีช่องว่าง

using System;

public class Demo
{
    public static void Main()
    {
        string str1 = "Amit";
        string str2 = " "; // ช่องว่าง ไม่ใช่สตริงว่าง
        
        Console.WriteLine("Is string1 null or empty? = " + string.IsNullOrEmpty(str1));
        Console.WriteLine("Is string2 null or empty? = " + string.IsNullOrEmpty(str2));
    }
}

ผลลัพธ์

Is string1 null or empty? = False
Is string2 null or empty? = False

ตัวอย่างที่ 2: null และ String.Empty

using System;

public class Demo
{
    public static void Main()
    {
        string str1 = null;
        string str2 = String.Empty; // เทียบเท่า ""
        
        Console.WriteLine("Is string1 null or empty? = " + string.IsNullOrEmpty(str1));
        Console.WriteLine("Is string2 null or empty? = " + string.IsNullOrEmpty(str2));
    }
}

ผลลัพธ์

Is string1 null or empty? = True
Is string2 null or empty? = True

ขยายความ: String.IsNullOrWhiteSpace()

ใน .NET 4.0+ มีเมธอด String.IsNullOrWhiteSpace() ที่ตรวจสอบเพิ่มเติมว่าสตริงประกอบด้วยเฉพาะ whitespace characters (space, tab, newline, ฯลฯ) ด้วย

string str = "   ";
Console.WriteLine(string.IsNullOrEmpty(str));      // False
Console.WriteLine(string.IsNullOrWhiteSpace(str)); // True

สรุป

  • IsNullOrEmpty : ตรวจสอบ null หรือ "" เท่านั้น
  • IsNullOrWhiteSpace : ตรวจสอบ null, "", หรือ whitespace only (แนะนำให้ใช้ตัวนี้สำหรับ validation input จากผู้ใช้)
  • เป็น static method เรียกผ่าน class String โดยตรง
  • ช่วยป้องกัน NullReferenceException เมื่อตรวจสอบก่อนใช้งานสตริง