.NET 4.5 comes with some of the major enhancements. Among them, one of the most important changes that has been made to every object is with the metadata of objects. In .NET 4.5 the System.Type object has been split into two separate classes:
Type : Provides a shallow view of the object structure, and mainly used to hold data.
TypeInfo : Gives a full view of an object, including its relationship to the parent and child classes
Even though old API still exists, when dealing with metadata of an object, TypeInfo gives a more light – weight implementation. The TypeInfo uses IEnumerable (State – Machine) construct to return metadata objects rather than arrays. The changes in line of TypeInfo provides lazy traversal of object metadata which can also take part in LINQ more easily.
public class Student { public string StudentName { get; set; } public int Class { get; set; } public string GetReport() { // add logic to return a string } }
Now, say you want to track what are the Properties and Methods defined on the class Student. You can easily get this info from TypeInfo object. The TypeInfo introduces DeclaredProperties, DeclaredMethods and DeclaredEvents to determine the Metadata associated to the class.
TypeInfo studentInfo = typeof(Student).GetTypeInfo(); IEnumerable<PropertyInfo> declaredProperties = studentInfo.DeclaredProperties; IEnumerable<MethodInfo> declaredMethods = studentInfo.DeclaredMethods; IEnumerable<EventInfo> declaredEvents = studentInfo.DeclaredEvents;
Thus rather than using the previous construct of typeof(Student).GetProperties() we can easily use this light weight and easy API to deal with metadata associated with the type.
Similarly, another important construct that we often use in Reflection is the Types present in an Assembly. To deal with this, you can use the new construct like this:
Assembly assembly = studentInfo.Assembly; IEnumerable<TypeInfo> declaredTypes = assembly.DefinedTypes;
In addition to the properties, the TypeInfo object also exposes a number of Methods each providing simple API to get metadata info from an object.
I hope this post comes helpful.
Thank you for reading.
You can find more about hidden secrets of Memory Management in my book (NET 4.5 Expert Development Cookbook)
Pingback: .NET Tips and Tricks from Daily .NET Tips – July and August 2013 Links | Abhijit's World of .NET