65.9K
CodeProject is changing. Read more.
Home

Get CustomAttributes the easy way....

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Apr 14, 2010

CPOL
viewsIcon

12406

A few extension methods to help out.....// Project: Salient.Reflection// http://salient.codeplex.comusing System;using System.Collections.Generic;using System.Linq;using System.Reflection;public static class AttributeHelpers{ /// /// Returns first...

A few extension methods to help out.....
// Project: Salient.Reflection
// http://salient.codeplex.com

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

public static class AttributeHelpers
{
    /// <summary>
    /// Returns first non-inherited custom attribute of type T
    /// </summary>
    public static T GetCustomAttribute<T>(this ICustomAttributeProvider provider)
        where T : Attribute
    {
        return GetCustomAttribute<T>(provider, false);
    }

    /// <summary>
    /// Returns first custom attribute of type T in the inheritance chain
    /// </summary>
    public static T GetCustomAttribute<T>(this ICustomAttributeProvider provider, bool inherited)
        where T : Attribute
    {
        return provider.GetCustomAttributes<T>(inherited).FirstOrDefault();
    }

    /// <summary>
    /// Returns all non-inherited custom attributes of type T 
    /// </summary>
    public static List<T> GetCustomAttributes<T>(this ICustomAttributeProvider provider) 
        where T : Attribute
    {
        return GetCustomAttributes<T>(provider, false);
    }

    /// <summary>
    /// Returns all custom attributes of type T in the inheritance chain
    /// </summary>
    public static List<T> GetCustomAttributes<T>(this ICustomAttributeProvider provider, bool inherited)
        where T : Attribute
    {
        return provider.GetCustomAttributes(typeof (T), inherited).Cast<T>().ToList();
    }
}

Thanks to Wouter Ballet.

To tonyt: Regarding linq abuse, although I have factored out the linq expression you complained about, it was intentional to deal with a casting issue. I invite you to check the previous revision and make that expression work in the order you propose without a lot of unnecessary bloat. But thanks for the feedback.