How do I use the 'using' statement

The using statement in C# is a convenient syntax that ensures the proper management of resources. It is primarily used with objects that implement the IDisposable interface, such as file streams and database connections. When the using statement is used, it guarantees that the object will be disposed of automatically when it is no longer needed, which helps to prevent memory leaks and other resource issues.

Here is a simple example of how to use the using statement to work with a file:

using (StreamReader reader = new StreamReader("file.txt")) { string content = reader.ReadToEnd(); Console.WriteLine(content); }

C# using statement IDisposable resource management file streams database connections memory management