← Back to C# Course | Chapter 15: Modern C# Features | Lesson 5 of 6

Nullable Reference Types (Concept) की जानकारी

Nullable reference types C# को यह चेतावनी देने देते हैं कि कुछ खाली हो सकता है, जैसे एक sign जो कहे 'यह box खाली हो सकता है, पहले जांचें'। यह आपको कुछ न होने के उपयोग से आने वाले आम crash से बचाता है।
Syntax
csharp
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 को अपने आप चेतावनी देने के लिए प्रेरित करता है।

Warning: Nullable reference type annotations सिर्फ compile-time hints हैं — वे runtime पर null को assign होने से नहीं रोकतीं, वे सिर्फ warnings produce करते हैं।

उदाहरण: Nullable Reference Types (Concept)

markup
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);
    }
}
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. यह सोचना कि string? runtime पर nulls रोकता है, जबकि यह सिर्फ compiler को warnings देता है; एक null अब भी निकल सकता है और एक NullReferenceException फेंक सकता है।
  2. ! null-forgiving operator से हर जगह warnings चुप कराना, जो null जांचने के बजाय सिर्फ समस्या छुपाता है।
  3. nullable context (project में <Nullable>enable</Nullable>) enable किए बिना warnings की उम्मीद करना, जिससे कुछ भी नहीं जांचा जाता।
🔒

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.