How to generate random colors in C#

By | February 1, 2013


In an application I required to generate some random colors. Writing these colors manually was not easy. So I decided to use .NET Reflection to generate colors using System.Drawing.Color class


We can use GetProperties method of Type class to get all the properties of Color class. It returns an array of PropertyInfo class. Follow these steps to create a RandomColor class to return a random color using NextColor method

Step:1 Write following code to create a RandomColor class after adding System.Reflection namespace

In this class, first all the properties of Color are retrieved in a PropertyInfo array. NextColor method picks a random property from PropertyInfo array and returns it after converting it to the Color type.

Step:2 To use this RandomColor class, create a new Windows Forms Application and write following in its load event

Here it adds 100 Labels in the form with random background color. Of course you need to write RandomColor class in the same namespace as the Form1 class

Form1 will look like following

Thanks for reading!

Leave a Reply

Your email address will not be published. Required fields are marked *