Skip to content

Instantly share code, notes, and snippets.

@ZacharyPatten
Created August 27, 2020 17:42
Show Gist options
  • Select an option

  • Save ZacharyPatten/776d46b140452c3c5d569e261a0b464d to your computer and use it in GitHub Desktop.

Select an option

Save ZacharyPatten/776d46b140452c3c5d569e261a0b464d to your computer and use it in GitHub Desktop.
An example of a helper method for console output settings.
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