Get Attribute for Member - CSharp System.Reflection

CSharp examples for System.Reflection:Member

Description

Get Attribute for Member

Demo Code


using System.Reflection;
using System.Linq;
using System.Collections.Generic;
using System;//  w  w  w  . ja  v a 2 s . c  om

public class Main{
        public static T GetAttribute<T>(this MemberInfo member, bool isRequired = true) where T : Attribute
        {
            var attribute = member.GetCustomAttributes(typeof(T), false).SingleOrDefault();

            if (attribute == null && isRequired)
            {
                throw new ArgumentException(string.Format("The {0} attribute must be defined on member {1}", typeof(T).Name, member.Name));
            }

            return (T)attribute;
        }
}

Related Tutorials