स्ट्रिंग को खाली इनिशियलाइज़ करने के तरीके
तरीका 1: null असाइन करना
string myStr = null;
तरीका 2: string.Empty उपयोग करना (अनुशंसित)
string myStr = string.Empty;
IsNullOrEmpty() से चेक करें:
if (string.IsNullOrEmpty(myStr)) {
Console.WriteLine("String is empty or null!");
}
पूर्ण कोड उदाहरण 1 (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!
पूर्ण कोड उदाहरण 2 (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!
तुलना:
| तरीका | मान | IsNullOrEmpty | IsNullOrWhiteSpace |
|---|---|---|---|
| null | कोई ऑब्जेक्ट नहीं | true | true |
| string.Empty | "" (खाली स्ट्रिंग ऑब्जेक्ट) | true | true |
| "" | "" (खाली स्ट्रिंग ऑब्जेक्ट) | true | true |
| " " | व्हाइटस्पेस | false | true |
सिफारिश: string.Empty उपयोग करें - इरादा स्पष्ट होता है और यह एक सिंगलटन है।