Wednesday, 25 August 2010

Dot.Net: Discover Attributs on Properties Sample

Question:
How to discover attributes in a class?
I do I find all properties that are annotated with marker attribute?


Answer:
You go by reflection.

Follow these steps:
  1. Get the Type of your class.
  2. Get all properties (public or non-public).
  3. Loop over the property collection and get the ones that have your custom attribute


The crucial method here is GetCustomAttributes().
It is overloaded and some overloads do not return what you would expect.
IMHO, the best way to use it, is to pass in the type of the attribute you are looking for.

Here is an example
using System.Reflection;

// get public properties, for non-public you need to pass a BindingFlag
MemberInfo[] infoList = typeof(MyClass).GetProperties();
foreach (MemberInfo info in infoList)
{
    object[] myAttributes = info.GetCustomAttributes(typeof(MyMarkerAttribute),true);
    bool hasMarker = myAttributes != null && myAttributes.Count() > 0;
    if (hasMarker)
    {
        // do something interesting
    };
}


Related: How to create a custom attribute in dot.net
.

No comments: