C# Interview Question #74
What is the using statement in C#?
Memory Management & Modern C# Mid-Level Intermediate
Quick Interview Answer
The using statement ensures that an IDisposable object is disposed when execution leaves its scope, including when an exception occurs.
Detailed Explanation
The using statement ensures that an IDisposable object is disposed when execution leaves its scope, including when an exception occurs.
Modern C# also supports using declarations, which dispose the resource at the end of the current scope.
For types implementing IAsyncDisposable, await using performs asynchronous cleanup.
Code Example
using (var stream = File.OpenRead("data.txt"))
{
// Use stream
}
// Using declaration
using var anotherStream = File.OpenRead("data.txt");