tags:

views:

86

answers:

6

I have a .Net object (in C#) which has properties named event1, event2 and so on.

I have to do some if-else on each of these. is there way i can loop over these. If these were controls i could have used the controls collection, but these are properties of an object.

Any help?

+2  A: 

It is probably clearest just to write it out manually. However, it is possible to do using reflection.

RossFabricant
A: 

Yes, you can use Reflection to get the PropertyInfo objects, interrogate the names and get the data you need.

JP Alioto
+2  A: 

Using reflection is your best bet, but it might be overkill for what you need. The snippet below is taken from msdn:

            foreach (MemberInfo mi in t.GetMembers() )
            {                                  

                // If the member is a property, display information about the
                //    property's accessor methods.
                if (mi.MemberType==MemberTypes.Property)
                {
                    PropertyInfo pmi = ((PropertyInfo) mi);
                    foreach ( MethodInfo am in pmi.GetAccessors() )
                    {
                        Display(indent+1, "Accessor method: {0}", am);
                    }
                }
            }
Lance Harper
+2  A: 

Assuming you know how many properties you're dealing with

    for(int eventIndex = 0; eventIndex < NUM_EVENTS; eventIndex++)
    {
        PropertyInfo eventPropertyInfo = 
            this.GetType().GetProperty("Event" + eventIndex);

        if (eventPropertyInfo.GetValue(this, null) == yourValue)
        {
             //Do Something here
        }
    }
MrTelly
+1  A: 

What's your reasoning for doing so? Is it to speed up development? You can use reflection as many have already suggested but it'd be much more effecient to simply reference the properties directly now instead of taking the performance penalty at runtime.

dkpatt
A: 

Reflection is easy solution but it may be slow depending on your application usage.

If reflection is slow, you can speed it up by Emiting the code. Not the easist thing to do but the end result is the same as if you wrote every line manually. Its also hard to maintain such code.

majkinetor