Click here to Skip to main content
11,648,785 members (82,498 online)
Click here to Skip to main content

Tagged as

Get Reflected use TypeDescriptor

, 16 Mar 2011 CPOL 12.6K 9
Rate this:
Please Sign up or sign in to vote.
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, ReflectionAPIs needs a hands experience and a lot of a heck to do a job. A number of classes that are built over the ReflectionAPIs 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 ComponentModelnamespace. 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

TypeDescriptoris a staticsealed 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 TypeDescriptoris 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.

TypeDescriptoris used to get information of a Type. To use it, you need to pass a component to its staticmethods. Let's 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 Buttonclass (you can use any class for this) and got the information (name in this example) from it. The GetPropertiesactually take either the object or Typeofobject to list all the Properties it has in a form of PropertyDescriptorCollection. Similarly, GetEventswill 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 EventInfoclass in Reflectionnamespace, EventDescriptoreventually 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 componentis a class that implements IComponent. In the above example, the ComponentTyperefers to Controlclass 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 EventDescriptorcan also be used to AddEventHandleror 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 RemoveEventHandlerto 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 PropertyDescriptorgives you the information about a Property. You can use PropertyDescriptorto 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, PropertyDescriptoralso 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 AddValueChangedtwice, and hence the b_clickmethod will be called twice (once for every AddValueChanged) for a single Textchanged (Textbeing the Default Property of the Buttonclass).

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

Some Additional Benefits

In addition to what is listed above, TypeDescriptoralso 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:

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 stringargument with dot(.)s and loop through to get value of each individual properties from the Objectand finally returning the actual value. Hence if you want to evaluate a big property stringlike:

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

It needs just a call to:

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Abhishek Sur
Architect
India India
Did you like his post?

Oh, lets go a bit further to know him better.
Visit his Website : www.abhisheksur.com to know more about Abhishek.

Abhishek also authored a book on .NET 4.5 Features and recommends you to read it, you will learn a lot from it.
http://bit.ly/EXPERTCookBook

Basically he is from India, who loves to explore the .NET world. He loves to code and in his leisure you always find him talking about technical stuffs.

Presently he is working in WPF, a new foundation to UI development, but mostly he likes to work on architecture and business classes. ASP.NET is one of his strength as well.
Have any problem? Write to him in his Forum.

You can also mail him directly to abhi2434@yahoo.com

Want a Coder like him for your project?
Drop him a mail to contact@abhisheksur.com

Visit His Blog

Dotnet Tricks and Tips



Dont forget to vote or share your comments about his Writing

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
Kunal_Chowdhury8-Feb-11 0:41
mvpKunal_Chowdhury8-Feb-11 0:41 
GeneralRe: My vote of 5 Pin
Member 1037950226-Jun-15 7:38
memberMember 1037950226-Jun-15 7:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150804.4 | Last Updated 16 Mar 2011
Article Copyright 2011 by Abhishek Sur
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid