Return the attribute object, you can get value from the object. - CSharp System

CSharp examples for System:Attribute

Description

Return the attribute object, you can get value from the object.

Demo Code


using System.Linq;

public class Main{
        /// <summary>
        /// Return the attribute object, you can get value from the object.
        /// </summary>
        /// <typeparam name="T">Attribute filter</typeparam>
        /// <param name="value">Class for the attribute apply.</param>
        /// <returns>Attrubute object</returns>
        public static T GetAttribute<T>(object value)
        {/*from w  ww  .  j  a v a 2 s .c  o  m*/
            if (value != null)
            {
                object[] attributes = value.GetType().GetCustomAttributes(typeof(T), true);
                if (attributes != null && attributes.Count() > 0)
                {
                    return (T)attributes[0];
                }
                else
                {
                    return default(T);
                }
            }
            else
            {
                return default(T);
            }
        }
}

Related Tutorials