What is the using statement used for, explain with example?
What is the using statement used for, explain with example?
Student
The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .
The
usingstatement in C# is used for automatically managing the lifetime of disposable resources—typically unmanaged resources like files, database connections, streams, etc.Purpose:
The
usingstatement ensures that the object’sDispose()method is called automatically, even if an exception occurs. This helps:Syntax:
Applies to:
Any class that implements the
IDisposableinterface, such as:StreamReader,FileStream,SqlConnectionXmlWriter,MemoryStream,HttpClientExample:
C# 8.0+:
In newer versions of C#, you can use a using declaration: