I'm wondering if there is a way to change the color of the text so that it looks like this when output

Name: Joe Blow
City: Denver
Score: 80

But I would like the text to be Yellow and the numbers to be White.

Console.WriteLine("Name: {0}", studentName);
Console.WriteLine("City: {0}", studentCity);
Console.WriteLine("Score: {0}",finalScore);

I know I could do it like the below code but I was hoping there might be a quicker way.

Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("Name: ");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(studentName);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("City: ");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(studentCity);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("Score: ");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(finalScore);

Thank you for any assistance!

You could turn it into a method, something like this:

static void Print(string title, string name)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write(title);
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(name);
        }
Comments
Thank you, this seems like a good approach. I was hoping for something like ToString that would work with color so I could keep the code to 3 lines.

Hi,
You can make a method for that:

public static void ColoredConsoleWrite(ConsoleColor color, string text)
{
    ConsoleColor originalColor = Console.ForegroundColor;
    Console.ForegroundColor = color;
    Console.Write(text);
    Console.ForegroundColor = originalColor;
}

and use like this

ColoredConsoleWrite(Yellow, "Name: ");
Console.WriteLine(studentName);
ColoredConsoleWrite(Yellow, "City: ");
Console.WriteLine(studentCity);

The initial foreground color is white.

ColoredConsoleWrite(Yellow, "Name: "); will not work, ColoredConsoleWrite(ConsoleColor.Yellow, "Name: "); will.
Please test code before posting.

This article has been dead for over six months. Start a new discussion instead.