Working with TypeDescriptor in C#

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.

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.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434

2 Comments to “Working with TypeDescriptor in C#”

  1. home improvement tips

    I have to voice my love for your kindness supporting men who require assistance with that matter. Your special commitment to passing the solution along turned out to be exceptionally helpful and have constantly empowered somebody like me to attain their desired goals. The informative advice signifies a lot to me and further more to my fellow workers. Thanks a ton; from all of us.

Comments are closed.