0

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!

3
Contributors
4
Replies
15
Views
2 Years
Discussion Span
Last Post by albucurus
Featured Replies
  • 1
    ddanbe 2,525   2 Years Ago

    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); } Read More

  • 1
    ddanbe 2,525   2 Years Ago

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

1

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);
        }
Votes + 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.
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.

1

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.