using Statement क्या है
using statement सुनिश्चित करता है कि किसी चीज़ के साथ काम खत्म होते ही उसकी साफ़-सफ़ाई हो जाए, जैसे fridge का दरवाज़ा अपने आप बंद होना। इसे files जैसी चीज़ों के लिए उपयोग किया जाता है जिन्हें release होना ज़रूरी है।
In this page:
Syntax
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
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());
}
}
}
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. #}
आम गलतियां
- किसी
usingstatement में ऐसी type का उपयोग करना जोIDisposableimplement नहीं करती, जो एक compile error है। usingblock खत्म होने के बाद disposed object का उपयोग करना, जोObjectDisposedExceptionफेंकता है।- streams या connections के लिए
usingभूल जाना, जिससे वे खुले रहते हैं।
चैप्टर सारांश
try,catch, औरfinallyerrors handle और cleanup करते हैं।- Exception types, custom exceptions,
throw, और exception filters (when) नियंत्रित करते हैं कि क्या फेंका और पकड़ा जाता है। usingstatement resources को अपने आप release करता है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: