ใน C# string.Empty และ String.Empty เป็นสิ่งเดียวกัน (string เป็น Alias ของ System.String) ใช้สำหรับ Initialize สตริงว่างแบบชัดเจน
Basic Usage
using System;
public class Program
{
public static void Main()
{
// ทั้งคู่เท่ากัน
string s1 = string.Empty;
string s2 = String.Empty;
string s3 = ""; // Literal - เหมือนกันแต่ Empty ชัดเจนกว่า
Console.WriteLine(s1 == s2); // True
Console.WriteLine(s1 == s3); // True
Console.WriteLine(string.IsNullOrEmpty(s1)); // True
}
}
string.IsNullOrEmpty vs IsNullOrWhiteSpace
string nullStr = null;
string emptyStr = "";
string whiteStr = " ";
string tabStr = "\t\n";
Console.WriteLine(string.IsNullOrEmpty(nullStr)); // True
Console.WriteLine(string.IsNullOrEmpty(emptyStr)); // True
Console.WriteLine(string.IsNullOrEmpty(whiteStr)); // False!
Console.WriteLine(string.IsNullOrEmpty(tabStr)); // False!
Console.WriteLine(string.IsNullOrWhiteSpace(nullStr)); // True
Console.WriteLine(string.IsNullOrWhiteSpace(emptyStr)); // True
Console.WriteLine(string.IsNullOrWhiteSpace(whiteStr)); // True
Console.WriteLine(string.IsNullOrWhiteSpace(tabStr)); // True
Memory & Performance
| วิธี | Allocation | Interned | แนะนำ |
|---|---|---|---|
string.Empty | ไม่ (Static Field) | ใช่ | ✓ ชัดเจน |
"" | ไม่ (Interned Literal) | ใช่ | ✓ สั้น กว้างขวาง |
new string(' ', 0) | ใช่ (New Object) | ไม่ | ✗ หลีกเลี่ยง |
Best Practices
// ✓ Good: ใช้ string.Empty สำหรับความชัดเจน
private string _name = string.Empty;
// ✓ Good: ใช้ "" สำหรับ Literal
var names = new[] { "John", "", "Jane" };
// ✓ Good: Check ก่อนใช้
public void SetName(string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("Name cannot be empty", nameof(name));
_name = name.Trim();
}
// ✗ Avoid: new string() ไม่จำเป็น
string bad = new string(' ', 0); // Wasteful
String Interning
// ทุก "" และ string.Empty ชี้ไป Instance เดียวกัน (Interned)
object.ReferenceEquals("", string.Empty); // True
object.ReferenceEquals("", ""); // True
// แต่ String ที่สร้าง Runtime ไม่ Intern โดย Default
string a = "He" + "llo"; // Compile-time Constant → Interned
string b = "Hel" + "lo"; // Runtime → อาจไม่ Intern
string.Intern(b); // Force Intern
object.ReferenceEquals(a, b); // True หลัง Intern
Default Value ของ string
class Example
{
string _field; // null (Default ของ Reference Type)
public Example()
{
// Constructor: ให้ Initialize ชัดเจน
_field = string.Empty; // หรือ ""
}
}
สรุป
string.Empty==String.Empty==""(Reference Equal)- ใช้
string.IsNullOrWhiteSpace()สำหรับ Validation (ครอบคลุม Space/Tab/Newline) - ใช้
string.IsNullOrEmpty()เมื่อต้องการแยก null/empty จาก whitespace - ไม่ต้อง `new string()` สำหรับ Empty String