Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using colors in console, how to store in a simplified notation

Tags:

c#

.net

console

The code below shows a line in different colors, but that's a lot of code to type just for one line and to repeat that all over a program again.
How exactly can I simplify this, so I don't need to write the same amount of code over and over?

Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write(">>> Order: ");
Console.ResetColor();
Console.Write("Data");
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.Write("Parity");
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write(" <<<");

Is there any way to store ... = Console.ForegroundColor = ConsoleColor.Cyan;?

"text" + color? + "text"; etc...

like image 515
Chris Avatar asked Apr 23 '10 10:04

Chris


People also ask

How do you color console logs?

To style the logs, you should place %c within the first argument of console. log(). It will pick up the next argument as a CSS style for the “%c” pattern argument text.

What is the syntax to print a text in the console?

Console. WriteLine("This is C#"); In this code line, we print the "This is C#" string to the console. To print a message to the console, we use the WriteLine method of the Console class.


1 Answers

It's not entirely clear what you mean, but you could always create helper methods:

public static void ColoredConsoleWrite(ConsoleColor color, string text)
{
    ConsoleColor originalColor = Console.ForegroundColor;
    Console.ForegroundColor = color;
    Console.Write(text);
    Console.ForegroundColor = originalColor;
}
like image 66
Jon Skeet Avatar answered Sep 22 '22 14:09

Jon Skeet