0 day streak
csharp / beginner
Snippet

Explicit Scope Cleanup

Using declarations ensure that objects implementing IDisposable (like file readers or network streams) are properly closed and cleared from memory as soon as they are no longer needed.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
using System.IO;
public class MemoryManager
{
public void ProcessText(string data)
{
// Automatically calls Dispose() when the block is exited
using var reader = new StringReader(data);
string firstLine = reader.ReadLine();
System.Console.WriteLine(firstLine);
}
}
Breakdown
1
using var reader = new StringReader(data);
The 'using' keyword guarantees that 'reader' is cleaned up at the end of the method scope.
2
string firstLine = reader.ReadLine();
Uses the resource while it is safely held in memory.