Saturday, 1 January 2011

Get dictionary of properties of a Type in CSharp

Question:
How do I get all public properties of a given type as a Dictionary?
How do I get properties of an object?
Get list of ProperyInfo for a given type.



Answer:
Use the System.Reflection namespace.

Follow these steps:
  1. Get the type directly or from the object by obj.GetType()
  2. Get the public properties.
  3. Fill the dictionary.

Here is an example
using System.Reflection;
    ...
    // 1)
    Type sourceType = typeof(MyType); 
    // 2)
    PropertyInfo[] pList = sourceType.GetProperties(); 
    Dictionary<string, PropertyInfo> _propertyDico = new Dictionary<string, PropertyInfo>(); 
    // 3)
    pList.ToList>PropertyInfo<().ForEach(pInfo=> _propertyDico.Add(pInfo.Name, pInfo)); 
 

Remark: Type.GetProperties() gets all public properties by default.
If you want to filter more precisely, you must pass BindingFlags when calling GetProperties method.

PropertyInfo[] propertyInfos = propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public  | BindingFlags.Static);

No comments: