Nov. 5th, 2006

andrewducker: (calvin dancing)
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
propertyName)
{
      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.
andrewducker: (cat chases butterfly)

(When LJ was down yesterday I had to resort to sending the link to people over MSN. Oh, how the mighty are fallen)
andrewducker: (roleplaying HP)
Cheers to [livejournal.com profile] despotliz for this link to some very cool picture mashups, which has just left me running late for [livejournal.com profile] 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.

September 2025

S M T W T F S
  12 3 456
78910111213
14151617181920
21222324252627
282930    

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Sep. 5th, 2025 12:21 am
Powered by Dreamwidth Studios