Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display formatted output in different colors using console.writeline

Tags:

c#

Is it possible to display formatted output in different colors:

console.WriteLine(“First {0} second{1} ”,  firstString, secondString)

I would like to display a variation while showing the output, like firstString in one color and secondString in another color.

like image 722
Developer Avatar asked Oct 17 '25 12:10

Developer


2 Answers

You should use Console.Write() if you want to use different colors in one line write like this:

Console.ForegroundColor = ConsoleColor.White;
Console.Write("First  ");
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write("{0} ", firstString);
Console.ForegroundColor = ConsoleColor.White;
Console.Write("second ");
Console.ForegroundColor = ConsoleColor.Green;
Console.Write("{0} ", secondString);
like image 117
teo van kot Avatar answered Oct 19 '25 00:10

teo van kot


You will need to do multiple Console.Write() calls and set colors for the console like so:

class Program {
    static void Main( string[] args ) {
      PrintColoredString( "First", "firstString", ConsoleColor.Green );
      PrintColoredString( "second", "secondString", ConsoleColor.Cyan );
      Console.ResetColor();
      Console.ReadKey();
    }

    private static void PrintColoredString(string key, string value, ConsoleColor color) {
      Console.ForegroundColor = color;
      Console.Write( "{0} {1} ", key, value );
    }
  }
like image 24
Cameron Tinker Avatar answered Oct 19 '25 00:10

Cameron Tinker