Pick a Random Brush

ojsim picture ojsim · May 21, 2011 · Viewed 23.2k times · Source

I'm looking for a method to pick a random Brush in Brushes collection (Aqua,Azure, ...Black,...). Any clue?

Answer

Edwin Groenendaal picture Edwin Groenendaal · May 21, 2011

You can use a bit of reflection, like so:

private Brush PickBrush()
{
    Brush result = Brushes.Transparent;

    Random rnd = new Random();

    Type brushesType = typeof(Brushes);

    PropertyInfo[] properties = brushesType.GetProperties();

    int random = rnd.Next(properties.Length);
    result = (Brush)properties[random].GetValue(null, null);

    return result;
}

That will do the trick. You may want to change the randomisation to use an external Random instance, instead of re-creating a new seed each time the method is called, as in my example.