0 day streak
csharp / beginner
Snippet

Using Statement Lifecycle

The 'using' statement is a best practice for managing memory with objects that implement IDisposable, ensuring resources like files or streams are closed automatically.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
using System.IO;
public class FileManager {
public void WriteTemporaryData() {
// The using block ensures the object is cleaned up immediately
using (var writer = new StringWriter()) {
writer.WriteLine("Hello World");
System.Console.WriteLine(writer.ToString());
}
}
}
Breakdown
1
using (var writer = new StringWriter())
Initializes a disposable resource that will be cleaned up at the end of the block.
2
}
At this closing brace, the object's Dispose() method is called automatically, freeing memory.