Tom
Tom

Reputation: 245

How to use reflection to cast a control as its type in order to modify properties?

Here's an example of what I currently do:

book enable = false;
foreach (Control c in controlList)
{
    if (c is MyTextBox)
    {
        (c as MyTextBox).Enabled = enable;
    }
    if...
    ...
}

Instead of having multiple if statements for every type of control, is there a way to get the type of the control in order to cast and then be able to access and set a property of that control?

Upvotes: 0

Views: 336

Answers (1)

Corey
Corey

Reputation: 16574

This is a great example of when not to use reflection.

The Control class contains an Enabled property that you can use for all descendants of Control to change their enabled state. So the simple way to change the enabled state of a collection of controls is:

bool enable = false;
foreach (Control c in controlList)
    c.Enabled = enable;

Or (now that you've mentioned the System.Web.UI namespace) you can do this for your WebControl-derived objects, assuming that the controlList collection can contain things that derive from Control but no necessarily from WebControl:

foreach (WebControl c in controlList.OfType<WebControl>())
    c.Enabled = enable;

Reflection is handy in some situations and you can do some pretty cool things with it. It's verbose and kind of tough to get your head around sometimes, and often it can be done more simply other ways.

Where it would be useful is if you had a collection of arbitrary objects of different types, some of which may have a bool Enabled property that you can set, but that there is no guarantee that they have a common base class that you can access the Enabled property on. Then you could do something like this:

bool enabled = false;
foreach (var obj in objectList)
{
    var tObj = obj.GetType();
    PropertyInfo piEnabled = tObj.GetProperty("Enabled", typeof(bool));
    if (piEnabled != null && piEnabled.CanWrite)
        piEnabled.SetValue(obj, enabled);
}

A lot more complex, a bit more opaque, and much, much slower than simply accessing the property via the Control parent class.

Upvotes: 2

Related Questions