Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Get Reflected use TypeDescriptor

0.00/5 (No votes)
16 Mar 2011 6  
Get Reflected use TypeDescriptor

Hi there. Reflection is one of the major libraries that runs over the CLR which lets you get information about a CLR type or an object during runtime. A large number of applications which are built today are taking advantage of Reflection to make their 3rd party codes plugin to their application dynamically. Reflection lets you explain objects and their behavior dynamically and without any static binding available to any of those objects.

But if you just need to get information about the objects at runtime, Reflection APIs needs a hands experience and a lot of a heck to do a job. A number of classes that are built over the Reflection APIs can be used to make your life easier while you code. One of the few libraries that are available with you that I must address is the classes within ComponentModel namespace. In this post, I will give you a sample demonstration of how you could use Descriptor types to get information about Properties, Attributes, Events, etc. without invoking a single line of Reflection calls. I hope you could use the code later while building your library.

TypeDescriptor

TypeDescriptor is a static sealed class which makes the starting point of the API. It exposes information of the object in terms of Properties, Attributes, Events, etc. in such a way that it could easily be managed and/or consumed. Even though the basic usage of TypeDescriptor is to get metadata of an object, yet it also exposes features to extend the object on the fly. Let us now discuss few capabilities of Descriptors with a little information about its usage.

TypeDescriptor is used to get information of a Type. To use it, you need to pass a component to its static methods. Let's put an example:

C#
Button b = new Button();

PropertyDescriptorCollection props = TypeDescriptor.GetProperties(b);
            
EventDescriptorCollection events = TypeDescriptor.GetEvents(b);
            
foreach(PropertyDescriptor pd in props)
    Console.WriteLine(pd.DisplayName);

foreach(EventDescriptor ed in events)
    Console.WriteLine(ed.Name);

Console.ReadLine();

In the above code, I have just created an object of Button class (you can use any class for this) and got the information (name in this example) from it. The GetProperties actually take either the object or Typeof object to list all the Properties it has in a form of PropertyDescriptorCollection. Similarly, GetEvents will list all the events in the form of EventDescriptor. Let's put a bit of both the Classes.

EventDescriptor

The class defines one single event for an object. In contrast to EventInfo class in Reflection namespace, EventDescriptor eventually does everything but gives you easier interface for the same. Some of the feature it exposes are:

  • ComponentType: Provides the actual type that derives a Component. A component is a class that implements IComponent. In the above example, the ComponentType refers to Control class as Buttons inherits it.
  • EventType: Represents the type of the delegate for the event.
  • IsMulticast: Represents if the event is a Multicast Event or not.
  • Name, Description, etc.

Note: To be used in any component designer such as Visual Studio Toolbox, every control should somehow implement IComponent interface. An IComponent and IContainer forms the logical parent child Visual in Visual Studio environment. In .NET, every control implements IComponent.

Basically EventDescriptor can also be used to AddEventHandler or RemoveEventHandler. For instance:

C#
EventDescriptor d = TypeDescriptor.GetDefaultEvent(b);
d.AddEventHandler(b, new EventHandler(b_Click));
b.PerformClick();
d.RemoveEventHandler(b, new EventHandler(b_Click));
b.PerformClick();

static void b_Click(object sender, EventArgs e)
{
    Console.WriteLine("Clicked");
}

It will eventually print Clicked for once on the Console as we use PerformClick. You should note, the message will be printed only once as we use RemoveEventHandler to remove the Click EventHandler.

Default Property or Event

If you don't know about Default property or Default Events, its just a special Attribute for a property or an event. DefaultPropertyAttribute is a special attribute which is set at class level which indicates the Property to be used by Default. It is used in Property Window of Visual Studio. DefaultEventAttribute is for events.

PropertyDescriptor

On the other hand, a PropertyDescriptor gives you the information about a Property. You can use PropertyDescriptor to SetValue, GetValue, ResetValue, etc. Let's put some text on the options you have with PropertyDescriptor.

  • IsReadOnly: Defines if the property is writable or not
  • PropertyType: Specifies the type object that relates the return type of the Property
  • IsLocalizable: Indicates whether the property should be localized
  • ShouldSerializeValue: Specifies if the value needs serializable

In addition to these, PropertyDescriptor also maintains a collection of Delegates internally which lets you notify when the property gets changed.

C#
PropertyDescriptor p = TypeDescriptor.GetDefaultProperty(b);
p.AddValueChanged(b, new EventHandler(b_Click));
p.AddValueChanged(b, new EventHandler(b_Click));
b.Text = "This is changed";
p.RemoveValueChanged(b, new EventHandler(b_Click));

static void b_Click(object sender, EventArgs e)
{
    Console.WriteLine("Changed");
}

Here I have intentionally added AddValueChanged twice, and hence the b_click method will be called twice (once for every AddValueChanged) for a single Text changed (Text being the Default Property of the Button class).

For your information: PropertyDescriptor comes very handy when dealing with Binding. Binding adds up ValueChanged event handler for each Property Changed, which might be used to update the property.

Some Additional Benefits

In addition to what is listed above, TypeDescriptor also lets you do lots of other work. It gives you an interface to get Attributes, define Association of one object with that of the other, etc. while most of the other benefits are related to Designer implementation of VS IDE. We will look back at them later in another post.

A Constructive Example (Evaluate your Object)

Well, after speaking about Descriptors, let me conclude the topic with a code which might come in handy for you. It is often a requirement to Evaluate a Property Tree from an object, but using Reflection often becomes very complex. Let's take a look at the code below:

C#
static T EvaluateProperty<T>(object container, string property)
{
    string[] expressionPath = property.Split('.');
    object baseobject = container;
    for (var i = 0; i < expressionPath.Length; i++)
    {
        string currentProperty = expressionPath[i];

        if (!string.IsNullOrEmpty(currentProperty))
        {
            PropertyDescriptorCollection descriptorcollection = 
				TypeDescriptor.GetProperties(baseobject);

            PropertyDescriptor descriptor = 
				descriptorcollection.Find(currentProperty, true);

            baseobject = descriptor.GetValue(baseobject);
        }
    }
    return (T)baseobject;
}

The code is very simple, I have split the text passed within the string argument with dot(.)s and loop through to get value of each individual properties from the Object and finally returning the actual value. Hence if you want to evaluate a big property string like:

C#
MyClass x = new MyClass();
EndResult result = x.MyProperty.MyNest1Property.MyNest2Property.MyNest3Property;

It needs just a call to:

C#
EndResult result = Evaluate<EndResult>
	(x, "MyProperty.MyNest1Property.MyNest2Property.MyNest3Property");

Conclusion

Many of 3rd party libraries or Microsoft control set are widely using TypeDescriptors to evaluate object. I hope the post gives you a brief idea about its usage. I hope you like the post.
Thank you.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here