Random Color is not really random..

MrLucky

Well-known member
Joined
Mar 5, 2006
Messages
47
Ive this function:

C#:
		public static Color GetRandomColor()
		{
			Random random = new Random();
			return Color.FromArgb(random.Next(256), random.Next(256), random.Next(256));
		}

I use this function here:

C#:
						int[] values;
						string[] legends;
						Color[] colors;
						
						values = new int[10];
						legends = new string[10];
						colors = new Color[10];
						
						int i = 0;
						while(reader.Read())
						{
							values[i] = Convert.ToInt32(reader.GetValue(reader.GetOrdinal("total_played")));
							legends[i] = reader.GetValue(reader.GetOrdinal("history_artist")) + " - " + reader.GetValue(reader.GetOrdinal("history_title"));
							colors[i] = ChartUtil.GetRandomColor();
							
							i += 1;
						}

So for every entry in DB, I thought there will be an other color.

But, in practice, every entry has the same color :confused:

How can I fix this?
 
The random class uses the time as a seed. You are probably creating the random objects so quickly that the computer clock does not advance throughout the process, meaning that you get the same seed every time. What you most likely will want to do is create one random object and re-use it so that this will never be a problem.
C#:
	static Random randomclr = new Random();
	public static Color GetRandomColor()
	{
		return Color.FromArgb(randomclr.Next(256), randomclr.Next(256), randomclr.Next(256));
	}
 
Well at first I was convinced there was something wrong elsewhere in your code, as from what youve posted I couldnt see an error, but then I gave it a quick test.

If you call GetRandomColor() from a button click and then click the button repeatedly, it always returns a different colour. However when called from a loop it returns the same colour for a set amount of time. If you had more items in your loop you would have discovered that after a certain amount the colour changes.

Assumably this is down to the way random generates a number. I remember back in the days of VB 6 you needed to pass a seed to avoid always getting the same value. To counter this many people passed a tickcount. Perhaps in .Net this is automatically done. Calling the method repeatedly over such a period of time however would mean the tickcount stays the same for several iterations of the call.

Im sorry, this doesnt solve your problem, but hopefully shines some light on why its happenign.
 
Back
Top