Nullable Reference Types (Concept) की जानकारी
In this page:
string? nullable = null; // may be null
string nonNullable = ""; // should never be null
if (nullable != null)
{
nullable.Length;
}
Nullable Reference Types (Concept)
C# 8 ने compile time पर अनजाने null-reference bugs पकड़ने के लिए nullable reference type annotations (string? का मतलब है "null हो सकता है", string का मतलब है "null नहीं होना चाहिए") introduce किए। चूंकि इसे enforce करने के लिए एक modern Roslyn-based compiler और project setting चाहिए, यह उदाहरण इसके बजाय underlying discipline manually दिखाता है: उपयोग से पहले explicit null checks, जो बिल्कुल वही है जो nullable-reference-types feature compiler को अपने आप चेतावनी देने के लिए प्रेरित करता है।
null को assign होने से नहीं रोकतीं, वे सिर्फ warnings produce करते हैं।उदाहरण: Nullable Reference Types (Concept)
using System;
class Program
{
static void PrintLength(string value)
{
if (value == null)
{
Console.WriteLine("Value was null, skipping");
return;
}
Console.WriteLine(value.Length);
}
static void Main(string[] args)
{
PrintLength("hello");
PrintLength(null);
}
}
Login to try C/C++/Java/PHP code in the editor
- यह सोचना कि
string?runtime पर nulls रोकता है, जबकि यह सिर्फ compiler को warnings देता है; एकnullअब भी निकल सकता है और एकNullReferenceExceptionफेंक सकता है। !null-forgiving operator से हर जगह warnings चुप कराना, जो null जांचने के बजाय सिर्फ समस्या छुपाता है।- nullable context (project में
<Nullable>enable</Nullable>) enable किए बिना warnings की उम्मीद करना, जिससे कुछ भी नहीं जांचा जाता।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: