November 5th, 2006

calvin dancing

Fun and games with reflection

I originally wrote this for the c# discussion forum at work, and if you don't use c# you'll be wanting to press the page-down button any second now...

Let's say you want to check whether a control is set to ReadOnly. The simple way is to say :
if(control.ReadOnly) {}

But, I hear you say, not all controls have a ReadOnly property. In fact, only TextBoxBase (and its descendants) have a ReadOnly property. Which is entirely true, most of the time. Not at all true, however, if the control has been subclassed and a ReadOnly property has been added. In which case what would be handy is a way of checking whether a control has a boolean ReadOnly property, and if it does returning it.

Which is where reflection comes in:

private PropertyType GetProperty(Object myObject, string
      Type typeInfo = myObject.GetType();
      PropertyInfo propertyInfo = typeInfo.GetProperty(propertyName);
      if (propertyInfo != null)
            object property = propertyInfo.GetValue(myObject, null);
            if (property is PropertyType)
                  return (PropertyType)property;
      return default(PropertyType);
which may look complex, but all it's doing is getting the Type Information for your object, checking to see if it has a property with the correct name and checking to see if it matches the correct return type. If it does then you get the information back, if not you get a default value (null for objects, zero for numbers, false for booleans).

You can call it to retrieve the Text property like so:
string title = CheckProperty(myForm, "Text");
or as a replacement for the original if statement at the top:
if(CheckProperty(control, "ReadOnly")) {}

And I wouldn't advise you to use it all the time (there being an overhead for reflection, and it being less clear than straightforward property checking), but it can be very handy on occasion.
roleplaying HP

Wrong pictures ahoy

Cheers to despotliz for this link to some very cool picture mashups, which has just left me running late for marrog's Buffy game. Warning - not worksafe, but very funny (and occasionally very, very wrong).

If the first picture doesn't do it for you, there is something wrong with you.