← Back to C# Course | Chapter 10: Exception Handling | Lesson 6 of 6

using Statement क्या है

using statement सुनिश्चित करता है कि किसी चीज़ के साथ काम खत्म होते ही उसकी साफ़-सफ़ाई हो जाए, जैसे fridge का दरवाज़ा अपने आप बंद होना। इसे files जैसी चीज़ों के लिए उपयोग किया जाता है जिन्हें release होना ज़रूरी है।

In this page:

  1. The using Statement
Syntax
csharp
using (ResourceType resource = new ResourceType())
{
    // use resource; Dispose() is called at the end
}

using var resource = new ResourceType();   // C# 8 declaration form

The using Statement

using statement यह सुनिश्चित करता है कि किसी IDisposable object का Dispose() method block खत्म होते ही अपने आप call हो, एक exception होने पर भी — आमतौर पर files, streams, और database connections के लिए उपयोग होता है।

यह Dispose() call करने वाले एक try/finally पर syntactic sugar है। यह manual cleanup भूलने से होने वाले resource leaks को रोकता है।

Note: IDisposable implement करने वाली कोई भी चीज़, जैसे StreamReader या StreamWriter, को using में wrap होना चाहिए।

उदाहरण: The using Statement

markup
using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string path = "notes.txt";

        using (StreamWriter writer = new StreamWriter(path))
        {
            writer.WriteLine("Hello from a using block");
        }

        using (StreamReader reader = new StreamReader(path))
        {
            Console.WriteLine(reader.ReadToEnd());
        }
    }
}
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. किसी using statement में ऐसी type का उपयोग करना जो IDisposable implement नहीं करती, जो एक compile error है।
  2. using block खत्म होने के बाद disposed object का उपयोग करना, जो ObjectDisposedException फेंकता है।
  3. streams या connections के लिए using भूल जाना, जिससे वे खुले रहते हैं।
चैप्टर सारांश
  • try, catch, और finally errors handle और cleanup करते हैं।
  • Exception types, custom exceptions, throw, और exception filters (when) नियंत्रित करते हैं कि क्या फेंका और पकड़ा जाता है।
  • using statement resources को अपने आप release करता है।
🔒

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.