This is a simple trick that I find makes my code more readable, and reduces the amount of code I need to write to explicitly scope *something*. It avoids the need to have to manually clean up, or reset some state. In the sample below I’ve used this to highlight the output on a console app to a user defined font colour. It’s really simple, DRY, and a great example:
Rather than writing this:
Console.WriteLine("Starting...");
Console.ForegroundColor = ConsoleColor.Yellow;
while(!_server.IsComplete)
{
Console.WriteLine(_server.Progress);
System.Threading.Thread.Sleep(1000);
}
Console.ResetColor();
I can now do this:
Console.WriteLine("Starting...");
using (new ScopedConsoleColour(ConsoleColor.Yellow))
{
while (!_server.IsComplete)
{
Console.WriteLine(_server.Progress);
System.Threading.Thread.Sleep(1000);
}
}
Based on a defined class of:
class ScopedConsoleColour : IDisposable
{
public ScopedConsoleColour(System.ConsoleColor colour)
{
Console.ForegroundColor = colour;
}
public void Dispose()
{
Console.ResetColor();
}
}
mplementing IDisposable ensures your state gets reset based on your scope. Another common use for this approach is for setting a wait cursor in a Windows form application. I’m sure there are many others great uses!
While this example is trivial, and only really saves 2 lines of code – I find it helps maintain readability as my project size increases, and reduced bugs if I forget to reset state because of an unexpected execution path – like when an exception gets thrown.