How to generate random colors in C#

      No Comments on How to generate random colors in C#

Introduction

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

Description

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

RandomColors Class c

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

RandomColors - Microsoft Visual Studio_2013-01-31_23-32-13

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

RandomColors

Thanks for reading!

Leave a Reply

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