namespace System
{
public static class TypeExtensionMethods
{
public static PropertyInfo[] GetAllProperties(this Type type)
{
List<Type> typeList = new List<Type>();
typeList.Add(type);
if (type.IsInterface)
{
typeList.AddRange(type.GetInterfaces());
}
List<PropertyInfo> propertyList = new List<PropertyInfo>();
foreach (Type interfaceType in typeList)
{
foreach (PropertyInfo property in interfaceType.GetProperties())
{
propertyList.Add(property);
}
}
return propertyList.ToArray();
}
}
}
Tuesday, May 19, 2009
Extension Method for Getting All Properties of a Type
I was writing a helper class that I needed to iterate through all of the properties of a type; later realized that my code didn't grab every property, specifically those that were interface types. Then I found this at beaucrawford.net (http://beaucrawford.net/post/Using-Reflection-to-get-inherited-properties-for-an-interface.aspx). I then turned it into an extension method. Behold:
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment