views:

1422

answers:

3

I'm trying to iterate over the Color class' Color properties.

Unfortunately its not in a collection so its just a class with a bunch of static properties.

Does anyone know if its possible to iterate over a class' properties be it static or object based?

+11  A: 

Yes, it's possible using reflection. Specific colors are defined as a static properties of the Color struct.

 PropertyInfo[] colors = typeof(Color).GetProperties(BindingFlags.Static|BindingFlags.Public);
 foreach(PropertyInfo pi in colors) {
     Color c = (Color)pi.GetValue(null, null);
     // do something here with the color
 }
arul
I would add: if (pi.PropertyType == typeof(Color))to future-proof against any new properties being added to Color.
ICR
+1  A: 

You might also be interested in this code

http://blog.guymahieu.com/2006/07/11/deep-reflection-of-properties-propertyreflector/

It provides an easy way to set/get properties by name. If you look into GetBestMatchingProperty you'll find the iteration over properties, that is done the same way as been posted before http://stackoverflow.com/questions/571982/iterating-over-class-properties/571988#571988

Bogdan Kanivets
A: 

Check this also:

http://www.wwwcoder.com/tabid/68/type/art/parentid/452/site/6086/default.aspx

Not exactly the same topic but related.

Jportelas