← Back to C# Course | Chapter 11: Generics | Lesson 6 of 6

Nullable<T> क्या है

एक nullable type किसी int जैसे number को बिल्कुल कोई value न रखने देता है, जैसे खाली छोड़ा गया form field। यह तब मददगार है जब जवाब अभी ज्ञात न हो।

In this page:

  1. Nullable<T>
Syntax
csharp
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>

markup
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);
        }
    }
}
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. #}
आम गलतियां
  1. किसी Nullable<T> पर .Value पढ़ना जिसकी कोई value नहीं, जो InvalidOperationException फेंकता है; HasValue जांचें।
  2. बिना cast या .Value के किसी nullable को non-nullable को assign करना।
  3. यह भूल जाना कि < या > से compare किया null false देता है।
चैप्टर सारांश
  • 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.