How do I create a random hex string that represents a color?

rahkim picture rahkim · Apr 8, 2009 · Viewed 38.7k times · Source

I'm generating some charts that need a hex string for the colors.

Example:

<dataseries name="ford" color="FF00FF" />

I'm creating these dynamically, so I would like to generate the hex code for each dataseries randomly.

What is the best way to do this?

Answer

Samuel picture Samuel · Apr 8, 2009

Easiest way is to use String.Format and use the hexadecimal format for the argument.

var random = new Random();
var color = String.Format("#{0:X6}", random.Next(0x1000000)); // = "#A197B9"