Fun and games with reflection
Nov. 5th, 2006 10:07 amI 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:
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.
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 GetPropertywhich 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).(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); }
You can call it to retrieve the Text property like so:
string title = CheckProperty
or as a replacement for the original if statement at the top:
if(CheckProperty
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.