13th May, 2011

Find classes marked with an attribute

Adding attributes to classes in .Net seems to be a good way to add meta data. I recently needed to find all classes in the assembly marked with an attribute.

Basically, you have to check every class in the assembly. Fortunately, we can use the .Where() and lambda functions to make the code a bit more elegant.

Let's define an attribute and apply it to a class.

namespace Demo
{
    [AttributeUsage(AttributeTargets.Class)]
    public class MyAttribute : System.Attribute { }

    [MyAttribute]
    public class DemoClass 
    {
        … // your code goes here
    }
}

Now, I don't want to search the entire assembly, only the current namespace, so I'll need an extra check.

public FindAllClasses() 
{
    Assembly currentAssembly = Assembly.GetExecutingAssembly();
    //
    // instantiate the attribute for comparison later
    //
    MyAttribute testAttribute = new MyAttribute();

    Type[] types = currentAssembly.GetTypes().Where(
        //
        // create a lambda function to return true when we are in the same namespace AND have the attribute
        //
        item => (
            //
            // check the namespace by text match
            //
            String.Equals(item.Namespace, "Demo", StringComparison.Ordinal) &&
            //
            // check for an instance of the attribute in the CustomAttributes list
            //
            item.GetCustomAttributes(false).Contains(testAttribute)
        )
    ).ToArray();
}

I don't know if this is the best way to do it, but it works.

 

Add Comment

The opinions expressed here are my own and not those of my employer.