กำหนดสตริงเป็น null:
string myStr = null;
ใช้ string.IsNullOrEmpty() ตรวจสอบ:
if (string.IsNullOrEmpty(myStr)) {
Console.WriteLine("String is empty or null!");
}
ตัวอย่างที่ 1
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:
ตัวอย่างที่ 2
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!