C# - Getting a list of every 'color' from System.Drawing or System.Windows.Media

In C# there are two colour structures in existence for making easy reference to a number of colours without the need to use RGB or Hex codes. However, they tend to be accessible only by typing their name - there isn't an easy way to simply obtain a random colour from these structures. But if you can obtain a list that contains them then you could pick a random colour from that list easily.

Iterating over all of the colours

In the System.Drawing namespace there exists an enum called 'KnownColor' which contains all of the colours which have names and are 'known' to the system. Why is this important? Well, because it's an enum, we can iterate through it as if it were a standard enum to obtain each known colour, like so.

Obtain a list containing System.Drawing.Color

We can add each colour from the known colours enum into a list of System.Drawing.Color fairly easily, as the System.Drawing.Color class contains a method for obtaining the colour from 'KnownColor', like so.

We can then add this to a list like so.

Converting System.Drawing.Color to System.Windows.Media.Color

All of this is very well if we want to work with the System.Drawing namespace and use its colour structures and classes. However, sometimes we may want to work with full list of System.Windows.Media.Color colours instead. Unfortunately, the closest I can find to 'KnownColor' in the System.Windows.Media namespace is the 'Brushes' which are a set of predefined 'SolidColorBrush' objects, rather than System.Windows.Media.Color colours. However, we can convert a System.Drawing.Color to a System.Windows.Media.Color relatively easily using the alpha, red, green, and blue values, like so.

Obtaining a list containing System.Windows.Media.Color

Using everything above, we can combine it to create a list that contains System.Windows.Media.Color colours rather than System.Drawing.Color colours, like so.


Using these methods you can obtain a list containing 174 colours from either the System.Drawing or System.Windows.Media namespaces. With these lists, you can then create random index generators to randomly access the colours, or iterate through the colours to assign all of them in order to certain objects as you wish.

Leave a Reply

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