namespace MiniTestRunner; /// /// Provides a scoped mechanism for temporarily changing console foreground and background colors. /// Automatically restores the previous colors when disposed. /// public readonly struct ConsoleColoring : IDisposable { /// /// Gets the console's foreground color before the change. /// public ConsoleColor PreviousForeground { get; } /// /// Gets the console's background color before the change, if available. /// public ConsoleColor? PreviousBackground { get; } /// /// Initializes a new instance of the struct and resets the console colors. /// public ConsoleColoring() { this.PreviousForeground = Console.ForegroundColor; this.PreviousBackground = Console.BackgroundColor; Console.ResetColor(); } /// /// Initializes a new instance of the struct and sets the console foreground and optionally background color. /// /// The foreground color to set. /// The optional background color to set. public ConsoleColoring(ConsoleColor foreground, ConsoleColor? background = null) { this.PreviousForeground = Console.ForegroundColor; Console.ForegroundColor = foreground; if (background is { } bgColor) { this.PreviousBackground = Console.BackgroundColor; Console.BackgroundColor = bgColor; } } /// /// Restores the console's foreground and background colors to their previous values. /// public void Dispose() { if (this.PreviousBackground is { } bgColor) { Console.BackgroundColor = bgColor; } Console.ForegroundColor = this.PreviousForeground; } }