Nullable<T> क्या है
एक nullable type किसी int जैसे number को बिल्कुल कोई value न रखने देता है, जैसे खाली छोड़ा गया form field। यह तब मददगार है जब जवाब अभी ज्ञात न हो।
In this page:
Syntax
int? variableName = null; // same as Nullable<int>
variableName.HasValue;
variableName.Value;
int result = variableName ?? defaultValue;
Nullable<T>
Nullable<T> (value types के लिए T? के रूप में लिखा गया) किसी int या bool जैसे value type को null से किसी value की अनुपस्थिति represent करने देता है, जो साधारण value types अन्यथा नहीं कर सकते।
.Value पढ़ने से पहले .HasValue जांचें, या एक default देने के लिए ?? का उपयोग करें। यह आमतौर पर optional data के लिए उपयोग होता है, जैसे कोई form field जो खाली छोड़ा जा सकता हो।
Warning:
वर्तमान में
null वाले किसी nullable पर .Value पढ़ना एक InvalidOperationException फेंकता है।उदाहरण: Nullable<T>
using System;
class Program
{
static void Main(string[] args)
{
int? age = null;
Console.WriteLine(age.HasValue);
Console.WriteLine(age ?? -1);
age = 25;
if (age.HasValue)
{
Console.WriteLine(age.Value);
}
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- किसी
Nullable<T>पर.Valueपढ़ना जिसकी कोई value नहीं, जोInvalidOperationExceptionफेंकता है;HasValueजांचें। - बिना cast या
.Valueके किसी nullable को non-nullable को assign करना। - यह भूल जाना कि
<या>से compare कियाnullfalse देता है।
चैप्टर सारांश
- Generic classes, methods, और interfaces सुरक्षित रूप से कई types के साथ काम करते हैं।
- Generic constraints सीमित करते हैं कि कौन सी types उपयोग की जा सकती हैं।
- Covariance और contravariance, और
Nullable<T>, generic types के व्यवहार को बढ़ाते हैं।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: