Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Brahma Prakash ShuklaRank #633 · 3.8K reputationPosted Nov 1, 2022, 10:31 AM EDT
“Using” statement calls – “dispose” method internally, whenever any exception occurred in any method call and in “Using” statement objects are read only and cannot be reassignable or modifiable.
Rajanikant HawaldarRank #110 · 20.3K reputationPosted Nov 2, 2022, 5:48 AM EDT
The reason for the using statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.
Microsoft documentation states that using has a double function, both as a directive and in statements. As a statement, as it was pointed out here in other answers, the keyword is basically syntactic sugar to determine a scope to dispose an IDisposable object. As a directive, it is routinely used to import namespaces and types. Also as a directive, you can create aliases for namespaces and types.
using System.IO; // using 'using' here class UsingStatement { static void Main() { var buffer = new char[50]; using (StreamReader streamReader = new("file1.txt")) // using 'using' here { int charsRead = 0; while (streamReader.Peek() != -1) { charsRead = streamReader.Read(buffer, 0, buffer.Length); // // Process characters read. // } } } }Naresh BeniwalRank #365 · 6.8K reputationPosted Nov 1, 2022, 10:35 AM EDT
https://www.c-sharpcorner.com/UploadFile/ff0d0f/using-keyword-in-C-Sharp/