Table of contents
What’s ‘Using’?
In C#, ‘using’ helps us clean up things we don’t need anymore, like open files or network connections. This helps our program run smoother and faster.
How Does It Work?
Here’s a simple example:
using (StreamReader reader = new StreamReader("file.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
In this code, we’re reading a file using StreamReader
. Once we’re done, ‘using’ automatically closes the file for us. This happens even if there’s an error in the code inside ‘using’. So, it’s a safe and easy way to manage resources.