Junior — Middle
What happens to resources when using the 'using' statement and calling Dispose in .NET?
sobes.tech AI
Answer from AI
In .NET, the using statement is used for automatic management of the lifetime of objects that implement the IDisposable interface. When exiting the using block, the Dispose() method is called, which releases unmanaged resources such as file handles, network connections, or frees memory occupied by the object.
This helps prevent resource leaks and ensures that resources are released promptly, even if an exception occurs within the block.
Example:
using(var stream = new FileStream("file.txt", FileMode.Open))
{
// Work with the file
} // Here, stream.Dispose() is called automatically
Calling Dispose() typically closes connections, frees memory, and performs other cleanup necessary for the proper termination of resource usage.