0 day streak
csharp / beginner
Snippet

Safe Resource Handling Scopes

Managing external resources like files or database connections requires careful cleanup. The 'using' statement ensures that objects implementing IDisposable are closed and released as soon as the block ends.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
using System.IO;
public class DataSaver {
public void WriteLog(string message) {
// The using block ensures the file is closed automatically
using (var writer = new StreamWriter("log.txt", true)) {
writer.WriteLine(message);
}
}
}
Breakdown
1
using (var writer = ...)
Initializes a resource that will be automatically disposed at the end of the curly braces.
2
writer.WriteLine(message)
Writes the provided text into the file stream.