Pages

Saturday, February 5, 2011

Get Reflected use TypeDescriptor

Hi there. Reflection is one of the major library that runs over the CLR which lets you get information about a CLR type or an object during runtime. A large number of application which is built today is taking advantage of Reflection to make their 3rd party codes plugin to their application dynamically. The Reflection lets you explain objects and its 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 heck to do a job. A number of classes that is 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. Lets put an example :


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 form of EventDescriptor. Lets 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 :


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. Lets 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 weather 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.

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 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 to 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 handy to you. It is often a requirement to Evaluate a Property Tree from an object, but using Reflection often becomes very complex. Lets  take a look at the code below :

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 each individual properties from the Object and finally returning the actual value. Hence if you want to evaluate a big property string like :

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

It need just a call to
EndResult result = Evaluate<EndResult>(x, "MyProperty.MyNest1Property.MyNest2Property.MyNest3Property");

Conclusion


Many of 3rd party libraries or MS 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.

1 comment:

  1. Nice post.

    It has been said that TypeDescriptor results in some overhead. For instance, in WPF, it is used to provide value change notifications without INotifyPropertyChanged but is regarded as a bad practise.

    ReplyDelete

Please make sure that the question you ask is somehow related to the post you choose. Otherwise you post your general question in Forum section.