Hzyf Hzyf - 3 months ago 17
ASP.NET (C#) Question

Creating random colors (System.Drawing.Color)

I am tring to create random drawing colors. There is an error. Could you help me about this code.

private Random random;

private void MainForm_Load(object sender, EventArgs e)
random = new Random();

private Color GetRandomColor()
return Color.FromArgb(random.Next(0, 255), random.Next(0,255),random.Next(0,255));
// The error is here

public SolidBrush brushGet()
SolidBrush oBrush = new SolidBrush(GetRandomColor());
return oBrush;


I don't see any problems with the above code, other than the Random object not being initialized before it is called to. There is also absolutely no need to initialize it in the Load event of the form; it can be done right when it's declared:

private static readonly Random Random = new Random();

Personally I'd not declare it on local scope, as far as I know you end up with the same value every time if you go about it that way. I also personally don't see the need of overcomplicating things; generating random numbers everytime and using the Color.FromAgb() method you should be fine.