How to generate random color?

15,007

Solution 1

If you want to use the standard console colors, you could mix the ConsoleColor Enumeration and Enum.GetNames() to get a random color. You'd then use Console.ForegroundColor and/or Console.BackgroundColor to change the color of the console.

// Store these as static variables; they will never be changing
String[] colorNames = ConsoleColor.GetNames(typeof(ConsoleColor));
int numColors = colorNames.Length;

// ...

Random rand = new Random(); // No need to create a new one for each iteration.
string[] x = new string[] { "", "", "" };
while(true) // This should probably be based on some condition, rather than 'true'
{
    // Get random ConsoleColor string
    string colorName = colorNames[rand.Next(numColors)];
    // Get ConsoleColor from string name
    ConsoleColor color = (ConsoleColor) Enum.Parse(typeof(ConsoleColor), colorName);

    // Assuming you want to set the Foreground here, not the Background
    Console.ForegroundColor = color;

    Console.WriteLine((x[rand.Next(x.Length)]));
    Thread.Sleep(100);
}

Solution 2

// Your array should be declared outside of the loop

string[] x = new string[] { "", "", "" }; 
Random random = new Random();     

// Also you should NEVER have an endless loop ;)
while (true)         
{            
     Console.ForegroundColor = Color.FromArgb(random.Next(255), random.Next(255), random.Next(255));

     Console.WriteLine((x[random.Next(x.Length)]));             
     Thread.Sleep(100);         
} 
Share:
15,007
user1445665
Author by

user1445665

Updated on June 04, 2022

Comments

  • user1445665
    user1445665 almost 2 years

    So I'm messing around in c#, and was wondering how to generate my string from an array, but with a random color:

        while (true)
            {
                string[] x = new string[] { "", "", "" };
                Random name = new Random();
                Console.WriteLine((x[name.Next(3)]));
                Thread.Sleep(100);
            }
    

    When I'm outputting x, I want it to be a random color. Thanks