Reflection on Anonymous Types

Using reflection on anonymous types is just like reflection on any other type.

Consider this simple anonymous object being instantiated:

var anonyObject = new
{
    Name = "Gabriel",
    Age = 31
};

If you want to know all the properties, it’s values and types you can query the object with the reflection classes like this:

//get the type of the anonymous object
Type anonyType = anonyObject.GetType();
//get all the properties info
PropertyInfo[] props = anonyType.GetProperties();
//display each of the properties info
foreach (var prop in props)
{
    Console.WriteLine("Name:{0}, Value:{1}, Type:{2}",prop.Name, 
        prop.GetValue(anonyObject, null), prop.PropertyType);
}

I just wanted to share this code because I’m going to use it in my next article in which I will talk about creating a helper method to transform the result from a Linq query that returns anonymous types to a DataTable.

Comments

Leave your comment

Author

Email (never displayed)

Website

Comment  
HTML is NOT allowed. Use regular line breaks and those will be respected.