पाठ 4 / 26
Types, var और Nullability
Variables declare करें, strings interpolate करें और nullable reference types संभालें।
Static types, inferred
C# statically typed है: हर variable का type compile time पर तय होता है। var में compiler type खुद निकालता है, पर type फिर भी तय रहता है। var n = 5; एक int है, dynamic नहीं।
डेटा, व्यवहार, async
ज़्यादातर .NET कोड डेटा को मॉडल करता है, collections बदलता है और धीमे I/O का इंतज़ार करता है।
Nullable reference types
Nullable चालू होने पर string का मतलब "कभी null नहीं" और string? का मतलब "null हो सकता है"। संभावित null को इस्तेमाल करने से पहले compiler चेतावनी देता है।
string name = "Asha";
string? nickname = null;
Console.WriteLine($"Hi {name}");
Console.WriteLine(nickname?.Length ?? 0);
Output:
Hi Asha 0
Warnings को ! से चुप न कराएँ
! operator compiler से कहता है "भरोसा रखो, null नहीं है"। अगर आप ग़लत हैं तो runtime पर NullReferenceException फिर भी आएगी। null check या ?. बेहतर है।
त्वरित जाँच: Nullable चालू होने पर `string?` का क्या मतलब है?
- string हमेशा खाली है
- string null हो सकता है
- string read-only है
- string एक number है
Answer
string null हो सकता है — `?` reference type को null होने की अनुमति देता है, इसलिए compiler आपसे उस स्थिति को संभालवाता है।