Extensions to get attribute information

Checking attributes on classes can be done by getting the type of the class and executing GetCustomAttributes() on it. You just need to iterate over the resulting object[] to find what you are interested in.

To simplify this a bit more, I wrote a couple of extension methods :

    static public class AttributeExtensions
    {
        static public T FindAttribute<T>(this object obj)
            where T : Attribute
        {
            return obj.GetType().GetCustomAttributes(true)
                .Where(attr => attr.GetType() == typeof(T))
                .Select(attr => attr as T).FirstOrDefault();
        }

        static public List<Attribute> GetAttributes(this object obj)
        {
            return obj.GetType().GetCustomAttributes(true).ConvertAllItems(c => c as Attribute).ToList();
        }

        static private IEnumerable<TOutput> ConvertAllItems<TInput, TOutput>(this IEnumerable<TInput> e, 
            Converter<TInput, TOutput> op)
        {
            foreach (TInput item in e)
            {
                yield return op(item);
            }
        }
    }
 

So, on a Person class like this

    [DataContract(Namespace="http://www.u2u.be/demo/entities")]
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    Person p = new Person() { Name = "John Doe", Age = 77 } ;

You can now find the DataContractAttribute by:

    DataContractAttribute attribute = p.FindAttribute<DataContractAttribute>();
    Console.WriteLine(attribute != null ? attribute.Namespace : "Attribute not found");
 

Or, to retrieve the list of attributes:

    List<Attribute> lst = p.GetAttributes();