การเริ่มต้นสตริงเป็นรายการว่าง -
string myStr = null;
ตอนนี้ ใช้วิธี IsNullOrEmpty() ในตัวเพื่อตรวจสอบว่ารายการว่างหรือไม่ -
if (string.IsNullOrEmpty(myStr)) {
Console.WriteLine("String is empty or null!");
} ให้เราดูรหัสที่สมบูรณ์ -
ตัวอย่าง
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
string myStr = null;
if (string.IsNullOrEmpty(myStr)) {
Console.WriteLine("String is empty or null!");
}
Console.ReadKey();
}
}
} ผลลัพธ์
String is empty or null!
อีกวิธีในการเริ่มต้นสตริงเป็นสตริงว่าง ให้ลองใช้รหัสต่อไปนี้ ที่นี่เราใช้ string.Empty -
ตัวอย่าง
using System;
namespace Demo {
public class Program {
public static void Main(string[] args) {
string myStr = string.Empty;
if (string.IsNullOrEmpty(myStr)) {
Console.WriteLine("String is empty or null!");
} else {
Console.WriteLine("String isn't empty or null!");
}
}
}
} ผลลัพธ์
String is empty or null!