Salient Solutions

wrasslin ones and nones for fun and profit - Sky Sanders' Blog
Get your own ranked flair here
posts - 92, comments - 102, trackbacks - 0

Get CustomAttributes the easy way....

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();
    }
}

Technorati tags: , ,

Print | posted on Wednesday, January 20, 2010 1:50 PM | Filed Under [ CodeProject-Tip ]

Feedback

No comments posted yet.

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 2 and 4 and type the answer here:

Powered by: