Created
August 27, 2020 17:42
-
-
Save ZacharyPatten/776d46b140452c3c5d569e261a0b464d to your computer and use it in GitHub Desktop.
An example of a helper method for console output settings.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| public class Program | |
| { | |
| public static void Main() | |
| { | |
| Console.WriteLine("hi mom"); | |
| ConsoleHelper.DoWith( | |
| action: () => Console.WriteLine("hi mom"), | |
| foreground: ConsoleColor.DarkRed); | |
| ConsoleHelper.DoWith( | |
| action: () => Console.WriteLine("hi mom"), | |
| background: ConsoleColor.Blue); | |
| ConsoleHelper.DoWith( | |
| action: () => Console.WriteLine("hi mom"), | |
| foreground: ConsoleColor.Black, | |
| background: ConsoleColor.Green); | |
| Console.WriteLine("Press [Enter] To Continue..."); | |
| Console.ReadLine(); | |
| } | |
| } | |
| public static class ConsoleHelper | |
| { | |
| public static void DoWith( | |
| Action action, | |
| ConsoleColor? foreground = null, | |
| ConsoleColor? background = null) | |
| { | |
| ConsoleColor? foregroundRevert = null; | |
| ConsoleColor? backgroundRevert = null; | |
| try | |
| { | |
| if (foreground.HasValue) | |
| { | |
| foregroundRevert = Console.ForegroundColor; | |
| Console.ForegroundColor = foreground.Value; | |
| } | |
| if (background.HasValue) | |
| { | |
| backgroundRevert = Console.BackgroundColor; | |
| Console.BackgroundColor = background.Value; | |
| } | |
| action(); | |
| } | |
| finally | |
| { | |
| if (foregroundRevert.HasValue) | |
| { | |
| Console.ForegroundColor = foregroundRevert.Value; | |
| } | |
| if (backgroundRevert.HasValue) | |
| { | |
| Console.BackgroundColor = backgroundRevert.Value; | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment