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!

Recommended Answers

All 4 Replies

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);
        }
commented: 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. +0

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.