Using statement
The using
statement is used to ensure that objects that use unmanaged resources (IDisposable
objects) are disposed of properly. This is particularly important for resources such as files, database connections, and streams, which should be released when they are no longer needed to avoid resource leaks.
Example:
using System;
using System.IO;
class Program
{
static void Main()
{
// Using statement to ensure the StreamReader is disposed of properly
using (StreamReader reader = new StreamReader("example.txt"))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
} // reader.Dispose() is called automatically here
}
}
In this example, the using
statement ensures that the StreamReader
object is disposed of once the block of code is done executing. This calls the Dispose
method on the StreamReader
object automatically.
Last updated