Reflection - get attribute name and value on property



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








198















I have a class, lets call it Book with a property called Name. With that property, I have an attribute associated with it.



public class Book

[Author("AuthorName")]
public string Name

get; private set;




In my main method, I'm using reflection and wish to get key value pair of each attribute for each property. So in this example, I'd expect to see "Author" for attribute name and "AuthorName" for the attribute value.



Question: How do I get the attribute name and value on my properties using Reflection?










share|improve this question






















  • whats happening when you are trying to access property's on that object through reflection , are you stuck somewhere or do you want code for reflection

    – kobe
    Jul 9 '11 at 21:50

















198















I have a class, lets call it Book with a property called Name. With that property, I have an attribute associated with it.



public class Book

[Author("AuthorName")]
public string Name

get; private set;




In my main method, I'm using reflection and wish to get key value pair of each attribute for each property. So in this example, I'd expect to see "Author" for attribute name and "AuthorName" for the attribute value.



Question: How do I get the attribute name and value on my properties using Reflection?










share|improve this question






















  • whats happening when you are trying to access property's on that object through reflection , are you stuck somewhere or do you want code for reflection

    – kobe
    Jul 9 '11 at 21:50













198












198








198


44






I have a class, lets call it Book with a property called Name. With that property, I have an attribute associated with it.



public class Book

[Author("AuthorName")]
public string Name

get; private set;




In my main method, I'm using reflection and wish to get key value pair of each attribute for each property. So in this example, I'd expect to see "Author" for attribute name and "AuthorName" for the attribute value.



Question: How do I get the attribute name and value on my properties using Reflection?










share|improve this question














I have a class, lets call it Book with a property called Name. With that property, I have an attribute associated with it.



public class Book

[Author("AuthorName")]
public string Name

get; private set;




In my main method, I'm using reflection and wish to get key value pair of each attribute for each property. So in this example, I'd expect to see "Author" for attribute name and "AuthorName" for the attribute value.



Question: How do I get the attribute name and value on my properties using Reflection?







c# reflection propertyinfo






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jul 9 '11 at 21:45









developerdougdeveloperdoug

2,48832436




2,48832436












  • whats happening when you are trying to access property's on that object through reflection , are you stuck somewhere or do you want code for reflection

    – kobe
    Jul 9 '11 at 21:50

















  • whats happening when you are trying to access property's on that object through reflection , are you stuck somewhere or do you want code for reflection

    – kobe
    Jul 9 '11 at 21:50
















whats happening when you are trying to access property's on that object through reflection , are you stuck somewhere or do you want code for reflection

– kobe
Jul 9 '11 at 21:50





whats happening when you are trying to access property's on that object through reflection , are you stuck somewhere or do you want code for reflection

– kobe
Jul 9 '11 at 21:50












14 Answers
14






active

oldest

votes


















238














Use typeof(Book).GetProperties() to get an array of PropertyInfo instances. Then use GetCustomAttribute() on each PropertyInfo to see if any of them have the Author Attribute type. If they do, you can get the name of the property from the property info and the attribute values from the attribute.



Something along these lines to scan a type for properties that have a specific attribute type and to return data in a dictionary (note that this can be made more dynamic by passing types into the routine):



public static Dictionary<string, string> GetAuthors()

Dictionary<string, string> _dict = new Dictionary<string, string>();

PropertyInfo props = typeof(Book).GetProperties();
foreach (PropertyInfo prop in props)

object attrs = prop.GetCustomAttributes(true);
foreach (object attr in attrs)

AuthorAttribute authAttr = attr as AuthorAttribute;
if (authAttr != null)

string propName = prop.Name;
string auth = authAttr.Name;

_dict.Add(propName, auth);




return _dict;






share|improve this answer




















  • 10





    I was hoping that I won't have to cast the attribute.

    – developerdoug
    Jul 9 '11 at 22:14











  • prop.GetCustomAttributes(true) only returns an object. If you don't want to cast then you could use reflection on the attribute instances themselves.

    – Adam Markowitz
    Jul 9 '11 at 22:37











  • What is AuthorAttribute here? Is it a class that is derived from Attribute? @Adam Markowitz

    – Sarath Avanavu
    Dec 6 '14 at 7:32






  • 1





    Yes. The OP is using a custom attribute named 'Author'. See here for an example: msdn.microsoft.com/en-us/library/sw480ze8.aspx

    – Adam Markowitz
    Dec 6 '14 at 21:03











  • The performance cost of casting the attribute is utterly insignificant compared to every other operation involved (except the null check and string assignments).

    – SilentSin
    Nov 21 '17 at 5:26


















90














To get all attributes of a property in a dictionary use this:



typeof(Book)
.GetProperty("Name")
.GetCustomAttributes(false)
.ToDictionary(a => a.GetType().Name, a => a);


remember to change to false to true if you want to include inheritted attributes as well.






share|improve this answer




















  • 3





    This does effectively the same thing as Adam's solution, but is far more concise.

    – Daniel Moore
    Jul 9 '11 at 22:58







  • 25





    Append .OfType<AuthorAttribue>() to the expression instead of ToDictionary if you only need Author attributes and want to skip a future cast

    – Adrian Zanescu
    Sep 27 '13 at 9:03











  • Will not this throw exception when there are two attributes of the same type on the same property?

    – Konstantin
    Feb 2 '17 at 16:46


















37














If you just want one specific Attribute value For instance Display Attribute you can use the following code:



var pInfo = typeof(Book).GetProperty("Name")
.GetCustomAttribute<DisplayAttribute>();
var name = pInfo.Name;





share|improve this answer
































    19














    You can use GetCustomAttributesData() and GetCustomAttributes():



    var attributeData = typeof(Book).GetProperty("Name").GetCustomAttributesData();
    var attributes = typeof(Book).GetProperty("Name").GetCustomAttributes(false);





    share|improve this answer


















    • 3





      what's the difference?

      – Prime By Design
      Apr 12 '16 at 16:07






    • 1





      @PrimeByDesign The former finds out how to instantiate the applied attributes. The latter actually instantiates those attributes.

      – HappyNomad
      Aug 31 '16 at 22:45


















    17














    I have solved similar problems by writing a Generic Extension Property Attribute Helper:



    using System;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;

    public static class AttributeHelper

    public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>(
    Expression<Func<T, TOut>> propertyExpression,
    Func<TAttribute, TValue> valueSelector)
    where TAttribute : Attribute

    var expression = (MemberExpression) propertyExpression.Body;
    var propertyInfo = (PropertyInfo) expression.Member;
    var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
    return attr != null ? valueSelector(attr) : default(TValue);




    Usage:



    var author = AttributeHelper.GetPropertyAttributeValue<Book, string, AuthorAttribute, string>(prop => prop.Name, attr => attr.Author);
    // author = "AuthorName"





    share|improve this answer




















    • 1





      How can i get description attribute from const Fields?

      – Amir
      Nov 2 '15 at 19:44






    • 1





      You will get a: Error 1775 Member 'Namespace.FieldName ' cannot be accessed with an instance reference; qualify it with a type name instead. If you need to do this, I suggest to change 'const' to 'readonly'.

      – Mikael Engver
      Nov 3 '15 at 9:47






    • 1





      You should have a lot more useful vote than that, honestly. It's a very nice and useful answer to many cases.

      – David Létourneau
      Jan 14 '16 at 16:26






    • 1





      Thanks @DavidLétourneau! One can only hope. Seems as if you helped a little bit in that.

      – Mikael Engver
      Jan 14 '16 at 19:39











    • :) Do you think it's possible to have the value of all attributes for one class by using your generic method and assign the value of the attribute to each properties ?

      – David Létourneau
      Jan 15 '16 at 18:51


















    12














    If you mean "for attributes that take one parameter, list the attribute-names and the parameter-value", then this is easier in .NET 4.5 via the CustomAttributeData API:



    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Reflection;

    public static class Program

    static void Main()

    PropertyInfo prop = typeof(Foo).GetProperty("Bar");
    var vals = GetPropertyAttributes(prop);
    // has: DisplayName = "abc", Browsable = false

    public static Dictionary<string, object> GetPropertyAttributes(PropertyInfo property)

    Dictionary<string, object> attribs = new Dictionary<string, object>();
    // look for attributes that takes one constructor argument
    foreach (CustomAttributeData attribData in property.GetCustomAttributesData())


    if(attribData.ConstructorArguments.Count == 1)

    string typeName = attribData.Constructor.DeclaringType.Name;
    if (typeName.EndsWith("Attribute")) typeName = typeName.Substring(0, typeName.Length - 9);
    attribs[typeName] = attribData.ConstructorArguments[0].Value;



    return attribs;



    class Foo

    [DisplayName("abc")]
    [Browsable(false)]
    public string Bar get; set;






    share|improve this answer






























      3














      private static Dictionary<string, string> GetAuthors()

      return typeof(Book).GetProperties()
      .SelectMany(prop => prop.GetCustomAttributes())
      .OfType<AuthorAttribute>()
      .ToDictionary(attribute => attribute.Name, attribute => attribute.Name);






      share|improve this answer






























        2














        Necromancing.

        For those that still have to maintain .NET 2.0, or those that want to do it without LINQ:



        public static object GetAttribute(System.Reflection.MemberInfo mi, System.Type t)
        objs.Length < 1)
        return null;

        return objs[0];




        public static T GetAttribute<T>(System.Reflection.MemberInfo mi)

        return (T)GetAttribute(mi, typeof(T));



        public delegate TResult GetValue_t<in T, out TResult>(T arg1);

        public static TValue GetAttributValue<TAttribute, TValue>(System.Reflection.MemberInfo mi, GetValue_t<TAttribute, TValue> value) where TAttribute : System.Attribute

        TAttribute objAtts = (TAttribute)mi.GetCustomAttributes(typeof(TAttribute), true);
        TAttribute att = (objAtts == null


        Example usage:



        System.Reflection.FieldInfo fi = t.GetField("PrintBackground");
        wkHtmlOptionNameAttribute att = GetAttribute<wkHtmlOptionNameAttribute>(fi);
        string name = GetAttributValue<wkHtmlOptionNameAttribute, string>(fi, delegate(wkHtmlOptionNameAttribute a) return a.Name;);


        or simply



        string aname = GetAttributValue<wkHtmlOptionNameAttribute, string>(fi, a => a.Name );





        share|improve this answer
































          1














          public static class PropertyInfoExtensions

          public static TValue GetAttributValue<TAttribute, TValue>(this PropertyInfo prop, Func<TAttribute, TValue> value) where TAttribute : Attribute

          var att = prop.GetCustomAttributes(
          typeof(TAttribute), true
          ).FirstOrDefault() as TAttribute;
          if (att != null)

          return value(att);

          return default(TValue);




          Usage:



           //get class properties with attribute [AuthorAttribute]
          var props = typeof(Book).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(AuthorAttribute)));
          foreach (var prop in props)

          string value = prop.GetAttributValue((AuthorAttribute a) => a.Name);



          or:



           //get class properties with attribute [AuthorAttribute]
          var props = typeof(Book).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(AuthorAttribute)));
          IList<string> values = props.Select(prop => prop.GetAttributValue((AuthorAttribute a) => a.Name)).Where(attr => attr != null).ToList();





          share|improve this answer






























            0














            foreach (var p in model.GetType().GetProperties())

            var valueOfDisplay =
            p.GetCustomAttributesData()
            .Any(a => a.AttributeType.Name == "DisplayNameAttribute") ?
            p.GetCustomAttribute<DisplayNameAttribute>().DisplayName :
            p.Name;



            In this example I used DisplayName instead of Author because it has a field named 'DisplayName' to be shown with a value.






            share|improve this answer
































              0














              Here are some static methods you can use to get the MaxLength, or any other attribute.



              using System;
              using System.Linq;
              using System.Reflection;
              using System.ComponentModel.DataAnnotations;
              using System.Linq.Expressions;

              public static class AttributeHelpers

              public static Int32 GetMaxLength<T>(Expression<Func<T,string>> propertyExpression)
              return GetPropertyAttributeValue<T,string,MaxLengthAttribute,Int32>(propertyExpression,attr => attr.Length);


              //Optional Extension method
              public static Int32 GetMaxLength<T>(this T instance,Expression<Func<T,string>> propertyExpression)
              return GetMaxLength<T>(propertyExpression);



              //Required generic method to get any property attribute from any class
              public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>(Expression<Func<T,TOut>> propertyExpression,Func<TAttribute,TValue> valueSelector) where TAttribute : Attribute
              var expression = (MemberExpression)propertyExpression.Body;
              var propertyInfo = (PropertyInfo)expression.Member;
              var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute),true).FirstOrDefault() as TAttribute;

              if (attr==null)
              throw new MissingMemberException(typeof(T).Name+"."+propertyInfo.Name,typeof(TAttribute).Name);


              return valueSelector(attr);





              Using the static method...



              var length = AttributeHelpers.GetMaxLength<Player>(x => x.PlayerName);


              Or using the optional extension method on an instance...



              var player = new Player();
              var length = player.GetMaxLength(x => x.PlayerName);


              Or using the full static method for any other attribute (StringLength for example)...



              var length = AttributeHelpers.GetPropertyAttributeValue<Player,string,StringLengthAttribute,Int32>(prop => prop.PlayerName,attr => attr.MaximumLength);


              Inspired by the Mikael Engver's answer.






              share|improve this answer
































                0














                to get attribute from enum, i'm using :



                 public enum ExceptionCodes

                [ExceptionCode(1000)]
                InternalError,


                public static (int code, string message) Translate(ExceptionCodes code)

                return code.GetType()
                .GetField(Enum.GetName(typeof(ExceptionCodes), code))
                .GetCustomAttributes(false).Where((attr) =>

                return (attr is ExceptionCodeAttribute);
                ).Select(customAttr =>

                var attr = (customAttr as ExceptionCodeAttribute);
                return (attr.Code, attr.FriendlyMessage);
                ).FirstOrDefault();



                // Using



                 var _message = Translate(code);





                share|improve this answer






























                  0














                  Just looking for the right place to put this piece of code.



                  let's say you have the following property:



                  [Display(Name = "Solar Radiation (Average)", ShortName = "SolarRadiationAvg")]
                  public int SolarRadiationAvgSensorId get; set;


                  And you want to get the ShortName value. You can do:



                  ((DisplayAttribute)(typeof(SensorsModel).GetProperty(SolarRadiationAvgSensorId).GetCustomAttribute(typeof(DisplayAttribute)))).ShortName;


                  Or to make it general:



                  internal static string GetPropertyAttributeShortName(string propertyName)

                  return ((DisplayAttribute)(typeof(SensorsModel).GetProperty(propertyName).GetCustomAttribute(typeof(DisplayAttribute)))).ShortName;






                  share|improve this answer






























                    0














                    While the above most upvoted answers definitely work, I'd suggest using a slightly different approach in some cases.



                    If your class has multiple properties with always the same attribute and you want to get those attributes sorted into a dictionary, here is how:



                    var dict = typeof(Book).GetProperties().ToDictionary(p => p.Name, p => p.GetCustomAttributes(typeof(AuthorName), false).Select(a => (AuthorName)a).FirstOrDefault());


                    This still uses cast but ensures that the cast will always work as you will only get the custom attributes of the type "AuthorName".
                    If you had multiple Attributes above answers would get a cast exception.






                    share|improve this answer























                      Your Answer






                      StackExchange.ifUsing("editor", function ()
                      StackExchange.using("externalEditor", function ()
                      StackExchange.using("snippets", function ()
                      StackExchange.snippets.init();
                      );
                      );
                      , "code-snippets");

                      StackExchange.ready(function()
                      var channelOptions =
                      tags: "".split(" "),
                      id: "1"
                      ;
                      initTagRenderer("".split(" "), "".split(" "), channelOptions);

                      StackExchange.using("externalEditor", function()
                      // Have to fire editor after snippets, if snippets enabled
                      if (StackExchange.settings.snippets.snippetsEnabled)
                      StackExchange.using("snippets", function()
                      createEditor();
                      );

                      else
                      createEditor();

                      );

                      function createEditor()
                      StackExchange.prepareEditor(
                      heartbeatType: 'answer',
                      autoActivateHeartbeat: false,
                      convertImagesToLinks: true,
                      noModals: true,
                      showLowRepImageUploadWarning: true,
                      reputationToPostImages: 10,
                      bindNavPrevention: true,
                      postfix: "",
                      imageUploader:
                      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                      allowUrls: true
                      ,
                      onDemand: true,
                      discardSelector: ".discard-answer"
                      ,immediatelyShowMarkdownHelp:true
                      );



                      );













                      draft saved

                      draft discarded


















                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6637679%2freflection-get-attribute-name-and-value-on-property%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown

























                      14 Answers
                      14






                      active

                      oldest

                      votes








                      14 Answers
                      14






                      active

                      oldest

                      votes









                      active

                      oldest

                      votes






                      active

                      oldest

                      votes









                      238














                      Use typeof(Book).GetProperties() to get an array of PropertyInfo instances. Then use GetCustomAttribute() on each PropertyInfo to see if any of them have the Author Attribute type. If they do, you can get the name of the property from the property info and the attribute values from the attribute.



                      Something along these lines to scan a type for properties that have a specific attribute type and to return data in a dictionary (note that this can be made more dynamic by passing types into the routine):



                      public static Dictionary<string, string> GetAuthors()

                      Dictionary<string, string> _dict = new Dictionary<string, string>();

                      PropertyInfo props = typeof(Book).GetProperties();
                      foreach (PropertyInfo prop in props)

                      object attrs = prop.GetCustomAttributes(true);
                      foreach (object attr in attrs)

                      AuthorAttribute authAttr = attr as AuthorAttribute;
                      if (authAttr != null)

                      string propName = prop.Name;
                      string auth = authAttr.Name;

                      _dict.Add(propName, auth);




                      return _dict;






                      share|improve this answer




















                      • 10





                        I was hoping that I won't have to cast the attribute.

                        – developerdoug
                        Jul 9 '11 at 22:14











                      • prop.GetCustomAttributes(true) only returns an object. If you don't want to cast then you could use reflection on the attribute instances themselves.

                        – Adam Markowitz
                        Jul 9 '11 at 22:37











                      • What is AuthorAttribute here? Is it a class that is derived from Attribute? @Adam Markowitz

                        – Sarath Avanavu
                        Dec 6 '14 at 7:32






                      • 1





                        Yes. The OP is using a custom attribute named 'Author'. See here for an example: msdn.microsoft.com/en-us/library/sw480ze8.aspx

                        – Adam Markowitz
                        Dec 6 '14 at 21:03











                      • The performance cost of casting the attribute is utterly insignificant compared to every other operation involved (except the null check and string assignments).

                        – SilentSin
                        Nov 21 '17 at 5:26















                      238














                      Use typeof(Book).GetProperties() to get an array of PropertyInfo instances. Then use GetCustomAttribute() on each PropertyInfo to see if any of them have the Author Attribute type. If they do, you can get the name of the property from the property info and the attribute values from the attribute.



                      Something along these lines to scan a type for properties that have a specific attribute type and to return data in a dictionary (note that this can be made more dynamic by passing types into the routine):



                      public static Dictionary<string, string> GetAuthors()

                      Dictionary<string, string> _dict = new Dictionary<string, string>();

                      PropertyInfo props = typeof(Book).GetProperties();
                      foreach (PropertyInfo prop in props)

                      object attrs = prop.GetCustomAttributes(true);
                      foreach (object attr in attrs)

                      AuthorAttribute authAttr = attr as AuthorAttribute;
                      if (authAttr != null)

                      string propName = prop.Name;
                      string auth = authAttr.Name;

                      _dict.Add(propName, auth);




                      return _dict;






                      share|improve this answer




















                      • 10





                        I was hoping that I won't have to cast the attribute.

                        – developerdoug
                        Jul 9 '11 at 22:14











                      • prop.GetCustomAttributes(true) only returns an object. If you don't want to cast then you could use reflection on the attribute instances themselves.

                        – Adam Markowitz
                        Jul 9 '11 at 22:37











                      • What is AuthorAttribute here? Is it a class that is derived from Attribute? @Adam Markowitz

                        – Sarath Avanavu
                        Dec 6 '14 at 7:32






                      • 1





                        Yes. The OP is using a custom attribute named 'Author'. See here for an example: msdn.microsoft.com/en-us/library/sw480ze8.aspx

                        – Adam Markowitz
                        Dec 6 '14 at 21:03











                      • The performance cost of casting the attribute is utterly insignificant compared to every other operation involved (except the null check and string assignments).

                        – SilentSin
                        Nov 21 '17 at 5:26













                      238












                      238








                      238







                      Use typeof(Book).GetProperties() to get an array of PropertyInfo instances. Then use GetCustomAttribute() on each PropertyInfo to see if any of them have the Author Attribute type. If they do, you can get the name of the property from the property info and the attribute values from the attribute.



                      Something along these lines to scan a type for properties that have a specific attribute type and to return data in a dictionary (note that this can be made more dynamic by passing types into the routine):



                      public static Dictionary<string, string> GetAuthors()

                      Dictionary<string, string> _dict = new Dictionary<string, string>();

                      PropertyInfo props = typeof(Book).GetProperties();
                      foreach (PropertyInfo prop in props)

                      object attrs = prop.GetCustomAttributes(true);
                      foreach (object attr in attrs)

                      AuthorAttribute authAttr = attr as AuthorAttribute;
                      if (authAttr != null)

                      string propName = prop.Name;
                      string auth = authAttr.Name;

                      _dict.Add(propName, auth);




                      return _dict;






                      share|improve this answer















                      Use typeof(Book).GetProperties() to get an array of PropertyInfo instances. Then use GetCustomAttribute() on each PropertyInfo to see if any of them have the Author Attribute type. If they do, you can get the name of the property from the property info and the attribute values from the attribute.



                      Something along these lines to scan a type for properties that have a specific attribute type and to return data in a dictionary (note that this can be made more dynamic by passing types into the routine):



                      public static Dictionary<string, string> GetAuthors()

                      Dictionary<string, string> _dict = new Dictionary<string, string>();

                      PropertyInfo props = typeof(Book).GetProperties();
                      foreach (PropertyInfo prop in props)

                      object attrs = prop.GetCustomAttributes(true);
                      foreach (object attr in attrs)

                      AuthorAttribute authAttr = attr as AuthorAttribute;
                      if (authAttr != null)

                      string propName = prop.Name;
                      string auth = authAttr.Name;

                      _dict.Add(propName, auth);




                      return _dict;







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Oct 8 '17 at 5:18









                      Sнаđошƒаӽ

                      7,475104567




                      7,475104567










                      answered Jul 9 '11 at 21:51









                      Adam MarkowitzAdam Markowitz

                      9,96732221




                      9,96732221







                      • 10





                        I was hoping that I won't have to cast the attribute.

                        – developerdoug
                        Jul 9 '11 at 22:14











                      • prop.GetCustomAttributes(true) only returns an object. If you don't want to cast then you could use reflection on the attribute instances themselves.

                        – Adam Markowitz
                        Jul 9 '11 at 22:37











                      • What is AuthorAttribute here? Is it a class that is derived from Attribute? @Adam Markowitz

                        – Sarath Avanavu
                        Dec 6 '14 at 7:32






                      • 1





                        Yes. The OP is using a custom attribute named 'Author'. See here for an example: msdn.microsoft.com/en-us/library/sw480ze8.aspx

                        – Adam Markowitz
                        Dec 6 '14 at 21:03











                      • The performance cost of casting the attribute is utterly insignificant compared to every other operation involved (except the null check and string assignments).

                        – SilentSin
                        Nov 21 '17 at 5:26












                      • 10





                        I was hoping that I won't have to cast the attribute.

                        – developerdoug
                        Jul 9 '11 at 22:14











                      • prop.GetCustomAttributes(true) only returns an object. If you don't want to cast then you could use reflection on the attribute instances themselves.

                        – Adam Markowitz
                        Jul 9 '11 at 22:37











                      • What is AuthorAttribute here? Is it a class that is derived from Attribute? @Adam Markowitz

                        – Sarath Avanavu
                        Dec 6 '14 at 7:32






                      • 1





                        Yes. The OP is using a custom attribute named 'Author'. See here for an example: msdn.microsoft.com/en-us/library/sw480ze8.aspx

                        – Adam Markowitz
                        Dec 6 '14 at 21:03











                      • The performance cost of casting the attribute is utterly insignificant compared to every other operation involved (except the null check and string assignments).

                        – SilentSin
                        Nov 21 '17 at 5:26







                      10




                      10





                      I was hoping that I won't have to cast the attribute.

                      – developerdoug
                      Jul 9 '11 at 22:14





                      I was hoping that I won't have to cast the attribute.

                      – developerdoug
                      Jul 9 '11 at 22:14













                      prop.GetCustomAttributes(true) only returns an object. If you don't want to cast then you could use reflection on the attribute instances themselves.

                      – Adam Markowitz
                      Jul 9 '11 at 22:37





                      prop.GetCustomAttributes(true) only returns an object. If you don't want to cast then you could use reflection on the attribute instances themselves.

                      – Adam Markowitz
                      Jul 9 '11 at 22:37













                      What is AuthorAttribute here? Is it a class that is derived from Attribute? @Adam Markowitz

                      – Sarath Avanavu
                      Dec 6 '14 at 7:32





                      What is AuthorAttribute here? Is it a class that is derived from Attribute? @Adam Markowitz

                      – Sarath Avanavu
                      Dec 6 '14 at 7:32




                      1




                      1





                      Yes. The OP is using a custom attribute named 'Author'. See here for an example: msdn.microsoft.com/en-us/library/sw480ze8.aspx

                      – Adam Markowitz
                      Dec 6 '14 at 21:03





                      Yes. The OP is using a custom attribute named 'Author'. See here for an example: msdn.microsoft.com/en-us/library/sw480ze8.aspx

                      – Adam Markowitz
                      Dec 6 '14 at 21:03













                      The performance cost of casting the attribute is utterly insignificant compared to every other operation involved (except the null check and string assignments).

                      – SilentSin
                      Nov 21 '17 at 5:26





                      The performance cost of casting the attribute is utterly insignificant compared to every other operation involved (except the null check and string assignments).

                      – SilentSin
                      Nov 21 '17 at 5:26













                      90














                      To get all attributes of a property in a dictionary use this:



                      typeof(Book)
                      .GetProperty("Name")
                      .GetCustomAttributes(false)
                      .ToDictionary(a => a.GetType().Name, a => a);


                      remember to change to false to true if you want to include inheritted attributes as well.






                      share|improve this answer




















                      • 3





                        This does effectively the same thing as Adam's solution, but is far more concise.

                        – Daniel Moore
                        Jul 9 '11 at 22:58







                      • 25





                        Append .OfType<AuthorAttribue>() to the expression instead of ToDictionary if you only need Author attributes and want to skip a future cast

                        – Adrian Zanescu
                        Sep 27 '13 at 9:03











                      • Will not this throw exception when there are two attributes of the same type on the same property?

                        – Konstantin
                        Feb 2 '17 at 16:46















                      90














                      To get all attributes of a property in a dictionary use this:



                      typeof(Book)
                      .GetProperty("Name")
                      .GetCustomAttributes(false)
                      .ToDictionary(a => a.GetType().Name, a => a);


                      remember to change to false to true if you want to include inheritted attributes as well.






                      share|improve this answer




















                      • 3





                        This does effectively the same thing as Adam's solution, but is far more concise.

                        – Daniel Moore
                        Jul 9 '11 at 22:58







                      • 25





                        Append .OfType<AuthorAttribue>() to the expression instead of ToDictionary if you only need Author attributes and want to skip a future cast

                        – Adrian Zanescu
                        Sep 27 '13 at 9:03











                      • Will not this throw exception when there are two attributes of the same type on the same property?

                        – Konstantin
                        Feb 2 '17 at 16:46













                      90












                      90








                      90







                      To get all attributes of a property in a dictionary use this:



                      typeof(Book)
                      .GetProperty("Name")
                      .GetCustomAttributes(false)
                      .ToDictionary(a => a.GetType().Name, a => a);


                      remember to change to false to true if you want to include inheritted attributes as well.






                      share|improve this answer















                      To get all attributes of a property in a dictionary use this:



                      typeof(Book)
                      .GetProperty("Name")
                      .GetCustomAttributes(false)
                      .ToDictionary(a => a.GetType().Name, a => a);


                      remember to change to false to true if you want to include inheritted attributes as well.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Aug 18 '15 at 17:26









                      Shimmy

                      50.9k101339550




                      50.9k101339550










                      answered Jul 9 '11 at 21:52









                      Mo ValipourMo Valipour

                      10.3k94981




                      10.3k94981







                      • 3





                        This does effectively the same thing as Adam's solution, but is far more concise.

                        – Daniel Moore
                        Jul 9 '11 at 22:58







                      • 25





                        Append .OfType<AuthorAttribue>() to the expression instead of ToDictionary if you only need Author attributes and want to skip a future cast

                        – Adrian Zanescu
                        Sep 27 '13 at 9:03











                      • Will not this throw exception when there are two attributes of the same type on the same property?

                        – Konstantin
                        Feb 2 '17 at 16:46












                      • 3





                        This does effectively the same thing as Adam's solution, but is far more concise.

                        – Daniel Moore
                        Jul 9 '11 at 22:58







                      • 25





                        Append .OfType<AuthorAttribue>() to the expression instead of ToDictionary if you only need Author attributes and want to skip a future cast

                        – Adrian Zanescu
                        Sep 27 '13 at 9:03











                      • Will not this throw exception when there are two attributes of the same type on the same property?

                        – Konstantin
                        Feb 2 '17 at 16:46







                      3




                      3





                      This does effectively the same thing as Adam's solution, but is far more concise.

                      – Daniel Moore
                      Jul 9 '11 at 22:58






                      This does effectively the same thing as Adam's solution, but is far more concise.

                      – Daniel Moore
                      Jul 9 '11 at 22:58





                      25




                      25





                      Append .OfType<AuthorAttribue>() to the expression instead of ToDictionary if you only need Author attributes and want to skip a future cast

                      – Adrian Zanescu
                      Sep 27 '13 at 9:03





                      Append .OfType<AuthorAttribue>() to the expression instead of ToDictionary if you only need Author attributes and want to skip a future cast

                      – Adrian Zanescu
                      Sep 27 '13 at 9:03













                      Will not this throw exception when there are two attributes of the same type on the same property?

                      – Konstantin
                      Feb 2 '17 at 16:46





                      Will not this throw exception when there are two attributes of the same type on the same property?

                      – Konstantin
                      Feb 2 '17 at 16:46











                      37














                      If you just want one specific Attribute value For instance Display Attribute you can use the following code:



                      var pInfo = typeof(Book).GetProperty("Name")
                      .GetCustomAttribute<DisplayAttribute>();
                      var name = pInfo.Name;





                      share|improve this answer





























                        37














                        If you just want one specific Attribute value For instance Display Attribute you can use the following code:



                        var pInfo = typeof(Book).GetProperty("Name")
                        .GetCustomAttribute<DisplayAttribute>();
                        var name = pInfo.Name;





                        share|improve this answer



























                          37












                          37








                          37







                          If you just want one specific Attribute value For instance Display Attribute you can use the following code:



                          var pInfo = typeof(Book).GetProperty("Name")
                          .GetCustomAttribute<DisplayAttribute>();
                          var name = pInfo.Name;





                          share|improve this answer















                          If you just want one specific Attribute value For instance Display Attribute you can use the following code:



                          var pInfo = typeof(Book).GetProperty("Name")
                          .GetCustomAttribute<DisplayAttribute>();
                          var name = pInfo.Name;






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Dec 25 '18 at 18:49









                          Lee Taylor

                          5,04672442




                          5,04672442










                          answered Sep 2 '14 at 23:41









                          maxspanmaxspan

                          4,57243862




                          4,57243862





















                              19














                              You can use GetCustomAttributesData() and GetCustomAttributes():



                              var attributeData = typeof(Book).GetProperty("Name").GetCustomAttributesData();
                              var attributes = typeof(Book).GetProperty("Name").GetCustomAttributes(false);





                              share|improve this answer


















                              • 3





                                what's the difference?

                                – Prime By Design
                                Apr 12 '16 at 16:07






                              • 1





                                @PrimeByDesign The former finds out how to instantiate the applied attributes. The latter actually instantiates those attributes.

                                – HappyNomad
                                Aug 31 '16 at 22:45















                              19














                              You can use GetCustomAttributesData() and GetCustomAttributes():



                              var attributeData = typeof(Book).GetProperty("Name").GetCustomAttributesData();
                              var attributes = typeof(Book).GetProperty("Name").GetCustomAttributes(false);





                              share|improve this answer


















                              • 3





                                what's the difference?

                                – Prime By Design
                                Apr 12 '16 at 16:07






                              • 1





                                @PrimeByDesign The former finds out how to instantiate the applied attributes. The latter actually instantiates those attributes.

                                – HappyNomad
                                Aug 31 '16 at 22:45













                              19












                              19








                              19







                              You can use GetCustomAttributesData() and GetCustomAttributes():



                              var attributeData = typeof(Book).GetProperty("Name").GetCustomAttributesData();
                              var attributes = typeof(Book).GetProperty("Name").GetCustomAttributes(false);





                              share|improve this answer













                              You can use GetCustomAttributesData() and GetCustomAttributes():



                              var attributeData = typeof(Book).GetProperty("Name").GetCustomAttributesData();
                              var attributes = typeof(Book).GetProperty("Name").GetCustomAttributes(false);






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Jul 9 '11 at 21:51









                              BrokenGlassBrokenGlass

                              135k22243296




                              135k22243296







                              • 3





                                what's the difference?

                                – Prime By Design
                                Apr 12 '16 at 16:07






                              • 1





                                @PrimeByDesign The former finds out how to instantiate the applied attributes. The latter actually instantiates those attributes.

                                – HappyNomad
                                Aug 31 '16 at 22:45












                              • 3





                                what's the difference?

                                – Prime By Design
                                Apr 12 '16 at 16:07






                              • 1





                                @PrimeByDesign The former finds out how to instantiate the applied attributes. The latter actually instantiates those attributes.

                                – HappyNomad
                                Aug 31 '16 at 22:45







                              3




                              3





                              what's the difference?

                              – Prime By Design
                              Apr 12 '16 at 16:07





                              what's the difference?

                              – Prime By Design
                              Apr 12 '16 at 16:07




                              1




                              1





                              @PrimeByDesign The former finds out how to instantiate the applied attributes. The latter actually instantiates those attributes.

                              – HappyNomad
                              Aug 31 '16 at 22:45





                              @PrimeByDesign The former finds out how to instantiate the applied attributes. The latter actually instantiates those attributes.

                              – HappyNomad
                              Aug 31 '16 at 22:45











                              17














                              I have solved similar problems by writing a Generic Extension Property Attribute Helper:



                              using System;
                              using System.Linq;
                              using System.Linq.Expressions;
                              using System.Reflection;

                              public static class AttributeHelper

                              public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>(
                              Expression<Func<T, TOut>> propertyExpression,
                              Func<TAttribute, TValue> valueSelector)
                              where TAttribute : Attribute

                              var expression = (MemberExpression) propertyExpression.Body;
                              var propertyInfo = (PropertyInfo) expression.Member;
                              var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
                              return attr != null ? valueSelector(attr) : default(TValue);




                              Usage:



                              var author = AttributeHelper.GetPropertyAttributeValue<Book, string, AuthorAttribute, string>(prop => prop.Name, attr => attr.Author);
                              // author = "AuthorName"





                              share|improve this answer




















                              • 1





                                How can i get description attribute from const Fields?

                                – Amir
                                Nov 2 '15 at 19:44






                              • 1





                                You will get a: Error 1775 Member 'Namespace.FieldName ' cannot be accessed with an instance reference; qualify it with a type name instead. If you need to do this, I suggest to change 'const' to 'readonly'.

                                – Mikael Engver
                                Nov 3 '15 at 9:47






                              • 1





                                You should have a lot more useful vote than that, honestly. It's a very nice and useful answer to many cases.

                                – David Létourneau
                                Jan 14 '16 at 16:26






                              • 1





                                Thanks @DavidLétourneau! One can only hope. Seems as if you helped a little bit in that.

                                – Mikael Engver
                                Jan 14 '16 at 19:39











                              • :) Do you think it's possible to have the value of all attributes for one class by using your generic method and assign the value of the attribute to each properties ?

                                – David Létourneau
                                Jan 15 '16 at 18:51















                              17














                              I have solved similar problems by writing a Generic Extension Property Attribute Helper:



                              using System;
                              using System.Linq;
                              using System.Linq.Expressions;
                              using System.Reflection;

                              public static class AttributeHelper

                              public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>(
                              Expression<Func<T, TOut>> propertyExpression,
                              Func<TAttribute, TValue> valueSelector)
                              where TAttribute : Attribute

                              var expression = (MemberExpression) propertyExpression.Body;
                              var propertyInfo = (PropertyInfo) expression.Member;
                              var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
                              return attr != null ? valueSelector(attr) : default(TValue);




                              Usage:



                              var author = AttributeHelper.GetPropertyAttributeValue<Book, string, AuthorAttribute, string>(prop => prop.Name, attr => attr.Author);
                              // author = "AuthorName"





                              share|improve this answer




















                              • 1





                                How can i get description attribute from const Fields?

                                – Amir
                                Nov 2 '15 at 19:44






                              • 1





                                You will get a: Error 1775 Member 'Namespace.FieldName ' cannot be accessed with an instance reference; qualify it with a type name instead. If you need to do this, I suggest to change 'const' to 'readonly'.

                                – Mikael Engver
                                Nov 3 '15 at 9:47






                              • 1





                                You should have a lot more useful vote than that, honestly. It's a very nice and useful answer to many cases.

                                – David Létourneau
                                Jan 14 '16 at 16:26






                              • 1





                                Thanks @DavidLétourneau! One can only hope. Seems as if you helped a little bit in that.

                                – Mikael Engver
                                Jan 14 '16 at 19:39











                              • :) Do you think it's possible to have the value of all attributes for one class by using your generic method and assign the value of the attribute to each properties ?

                                – David Létourneau
                                Jan 15 '16 at 18:51













                              17












                              17








                              17







                              I have solved similar problems by writing a Generic Extension Property Attribute Helper:



                              using System;
                              using System.Linq;
                              using System.Linq.Expressions;
                              using System.Reflection;

                              public static class AttributeHelper

                              public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>(
                              Expression<Func<T, TOut>> propertyExpression,
                              Func<TAttribute, TValue> valueSelector)
                              where TAttribute : Attribute

                              var expression = (MemberExpression) propertyExpression.Body;
                              var propertyInfo = (PropertyInfo) expression.Member;
                              var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
                              return attr != null ? valueSelector(attr) : default(TValue);




                              Usage:



                              var author = AttributeHelper.GetPropertyAttributeValue<Book, string, AuthorAttribute, string>(prop => prop.Name, attr => attr.Author);
                              // author = "AuthorName"





                              share|improve this answer















                              I have solved similar problems by writing a Generic Extension Property Attribute Helper:



                              using System;
                              using System.Linq;
                              using System.Linq.Expressions;
                              using System.Reflection;

                              public static class AttributeHelper

                              public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>(
                              Expression<Func<T, TOut>> propertyExpression,
                              Func<TAttribute, TValue> valueSelector)
                              where TAttribute : Attribute

                              var expression = (MemberExpression) propertyExpression.Body;
                              var propertyInfo = (PropertyInfo) expression.Member;
                              var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
                              return attr != null ? valueSelector(attr) : default(TValue);




                              Usage:



                              var author = AttributeHelper.GetPropertyAttributeValue<Book, string, AuthorAttribute, string>(prop => prop.Name, attr => attr.Author);
                              // author = "AuthorName"






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Dec 13 '17 at 10:06

























                              answered Sep 10 '15 at 12:02









                              Mikael EngverMikael Engver

                              3,08433344




                              3,08433344







                              • 1





                                How can i get description attribute from const Fields?

                                – Amir
                                Nov 2 '15 at 19:44






                              • 1





                                You will get a: Error 1775 Member 'Namespace.FieldName ' cannot be accessed with an instance reference; qualify it with a type name instead. If you need to do this, I suggest to change 'const' to 'readonly'.

                                – Mikael Engver
                                Nov 3 '15 at 9:47






                              • 1





                                You should have a lot more useful vote than that, honestly. It's a very nice and useful answer to many cases.

                                – David Létourneau
                                Jan 14 '16 at 16:26






                              • 1





                                Thanks @DavidLétourneau! One can only hope. Seems as if you helped a little bit in that.

                                – Mikael Engver
                                Jan 14 '16 at 19:39











                              • :) Do you think it's possible to have the value of all attributes for one class by using your generic method and assign the value of the attribute to each properties ?

                                – David Létourneau
                                Jan 15 '16 at 18:51












                              • 1





                                How can i get description attribute from const Fields?

                                – Amir
                                Nov 2 '15 at 19:44






                              • 1





                                You will get a: Error 1775 Member 'Namespace.FieldName ' cannot be accessed with an instance reference; qualify it with a type name instead. If you need to do this, I suggest to change 'const' to 'readonly'.

                                – Mikael Engver
                                Nov 3 '15 at 9:47






                              • 1





                                You should have a lot more useful vote than that, honestly. It's a very nice and useful answer to many cases.

                                – David Létourneau
                                Jan 14 '16 at 16:26






                              • 1





                                Thanks @DavidLétourneau! One can only hope. Seems as if you helped a little bit in that.

                                – Mikael Engver
                                Jan 14 '16 at 19:39











                              • :) Do you think it's possible to have the value of all attributes for one class by using your generic method and assign the value of the attribute to each properties ?

                                – David Létourneau
                                Jan 15 '16 at 18:51







                              1




                              1





                              How can i get description attribute from const Fields?

                              – Amir
                              Nov 2 '15 at 19:44





                              How can i get description attribute from const Fields?

                              – Amir
                              Nov 2 '15 at 19:44




                              1




                              1





                              You will get a: Error 1775 Member 'Namespace.FieldName ' cannot be accessed with an instance reference; qualify it with a type name instead. If you need to do this, I suggest to change 'const' to 'readonly'.

                              – Mikael Engver
                              Nov 3 '15 at 9:47





                              You will get a: Error 1775 Member 'Namespace.FieldName ' cannot be accessed with an instance reference; qualify it with a type name instead. If you need to do this, I suggest to change 'const' to 'readonly'.

                              – Mikael Engver
                              Nov 3 '15 at 9:47




                              1




                              1





                              You should have a lot more useful vote than that, honestly. It's a very nice and useful answer to many cases.

                              – David Létourneau
                              Jan 14 '16 at 16:26





                              You should have a lot more useful vote than that, honestly. It's a very nice and useful answer to many cases.

                              – David Létourneau
                              Jan 14 '16 at 16:26




                              1




                              1





                              Thanks @DavidLétourneau! One can only hope. Seems as if you helped a little bit in that.

                              – Mikael Engver
                              Jan 14 '16 at 19:39





                              Thanks @DavidLétourneau! One can only hope. Seems as if you helped a little bit in that.

                              – Mikael Engver
                              Jan 14 '16 at 19:39













                              :) Do you think it's possible to have the value of all attributes for one class by using your generic method and assign the value of the attribute to each properties ?

                              – David Létourneau
                              Jan 15 '16 at 18:51





                              :) Do you think it's possible to have the value of all attributes for one class by using your generic method and assign the value of the attribute to each properties ?

                              – David Létourneau
                              Jan 15 '16 at 18:51











                              12














                              If you mean "for attributes that take one parameter, list the attribute-names and the parameter-value", then this is easier in .NET 4.5 via the CustomAttributeData API:



                              using System.Collections.Generic;
                              using System.ComponentModel;
                              using System.Reflection;

                              public static class Program

                              static void Main()

                              PropertyInfo prop = typeof(Foo).GetProperty("Bar");
                              var vals = GetPropertyAttributes(prop);
                              // has: DisplayName = "abc", Browsable = false

                              public static Dictionary<string, object> GetPropertyAttributes(PropertyInfo property)

                              Dictionary<string, object> attribs = new Dictionary<string, object>();
                              // look for attributes that takes one constructor argument
                              foreach (CustomAttributeData attribData in property.GetCustomAttributesData())


                              if(attribData.ConstructorArguments.Count == 1)

                              string typeName = attribData.Constructor.DeclaringType.Name;
                              if (typeName.EndsWith("Attribute")) typeName = typeName.Substring(0, typeName.Length - 9);
                              attribs[typeName] = attribData.ConstructorArguments[0].Value;



                              return attribs;



                              class Foo

                              [DisplayName("abc")]
                              [Browsable(false)]
                              public string Bar get; set;






                              share|improve this answer



























                                12














                                If you mean "for attributes that take one parameter, list the attribute-names and the parameter-value", then this is easier in .NET 4.5 via the CustomAttributeData API:



                                using System.Collections.Generic;
                                using System.ComponentModel;
                                using System.Reflection;

                                public static class Program

                                static void Main()

                                PropertyInfo prop = typeof(Foo).GetProperty("Bar");
                                var vals = GetPropertyAttributes(prop);
                                // has: DisplayName = "abc", Browsable = false

                                public static Dictionary<string, object> GetPropertyAttributes(PropertyInfo property)

                                Dictionary<string, object> attribs = new Dictionary<string, object>();
                                // look for attributes that takes one constructor argument
                                foreach (CustomAttributeData attribData in property.GetCustomAttributesData())


                                if(attribData.ConstructorArguments.Count == 1)

                                string typeName = attribData.Constructor.DeclaringType.Name;
                                if (typeName.EndsWith("Attribute")) typeName = typeName.Substring(0, typeName.Length - 9);
                                attribs[typeName] = attribData.ConstructorArguments[0].Value;



                                return attribs;



                                class Foo

                                [DisplayName("abc")]
                                [Browsable(false)]
                                public string Bar get; set;






                                share|improve this answer

























                                  12












                                  12








                                  12







                                  If you mean "for attributes that take one parameter, list the attribute-names and the parameter-value", then this is easier in .NET 4.5 via the CustomAttributeData API:



                                  using System.Collections.Generic;
                                  using System.ComponentModel;
                                  using System.Reflection;

                                  public static class Program

                                  static void Main()

                                  PropertyInfo prop = typeof(Foo).GetProperty("Bar");
                                  var vals = GetPropertyAttributes(prop);
                                  // has: DisplayName = "abc", Browsable = false

                                  public static Dictionary<string, object> GetPropertyAttributes(PropertyInfo property)

                                  Dictionary<string, object> attribs = new Dictionary<string, object>();
                                  // look for attributes that takes one constructor argument
                                  foreach (CustomAttributeData attribData in property.GetCustomAttributesData())


                                  if(attribData.ConstructorArguments.Count == 1)

                                  string typeName = attribData.Constructor.DeclaringType.Name;
                                  if (typeName.EndsWith("Attribute")) typeName = typeName.Substring(0, typeName.Length - 9);
                                  attribs[typeName] = attribData.ConstructorArguments[0].Value;



                                  return attribs;



                                  class Foo

                                  [DisplayName("abc")]
                                  [Browsable(false)]
                                  public string Bar get; set;






                                  share|improve this answer













                                  If you mean "for attributes that take one parameter, list the attribute-names and the parameter-value", then this is easier in .NET 4.5 via the CustomAttributeData API:



                                  using System.Collections.Generic;
                                  using System.ComponentModel;
                                  using System.Reflection;

                                  public static class Program

                                  static void Main()

                                  PropertyInfo prop = typeof(Foo).GetProperty("Bar");
                                  var vals = GetPropertyAttributes(prop);
                                  // has: DisplayName = "abc", Browsable = false

                                  public static Dictionary<string, object> GetPropertyAttributes(PropertyInfo property)

                                  Dictionary<string, object> attribs = new Dictionary<string, object>();
                                  // look for attributes that takes one constructor argument
                                  foreach (CustomAttributeData attribData in property.GetCustomAttributesData())


                                  if(attribData.ConstructorArguments.Count == 1)

                                  string typeName = attribData.Constructor.DeclaringType.Name;
                                  if (typeName.EndsWith("Attribute")) typeName = typeName.Substring(0, typeName.Length - 9);
                                  attribs[typeName] = attribData.ConstructorArguments[0].Value;



                                  return attribs;



                                  class Foo

                                  [DisplayName("abc")]
                                  [Browsable(false)]
                                  public string Bar get; set;







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Oct 25 '12 at 20:09









                                  Marc GravellMarc Gravell

                                  794k19821612565




                                  794k19821612565





















                                      3














                                      private static Dictionary<string, string> GetAuthors()

                                      return typeof(Book).GetProperties()
                                      .SelectMany(prop => prop.GetCustomAttributes())
                                      .OfType<AuthorAttribute>()
                                      .ToDictionary(attribute => attribute.Name, attribute => attribute.Name);






                                      share|improve this answer



























                                        3














                                        private static Dictionary<string, string> GetAuthors()

                                        return typeof(Book).GetProperties()
                                        .SelectMany(prop => prop.GetCustomAttributes())
                                        .OfType<AuthorAttribute>()
                                        .ToDictionary(attribute => attribute.Name, attribute => attribute.Name);






                                        share|improve this answer

























                                          3












                                          3








                                          3







                                          private static Dictionary<string, string> GetAuthors()

                                          return typeof(Book).GetProperties()
                                          .SelectMany(prop => prop.GetCustomAttributes())
                                          .OfType<AuthorAttribute>()
                                          .ToDictionary(attribute => attribute.Name, attribute => attribute.Name);






                                          share|improve this answer













                                          private static Dictionary<string, string> GetAuthors()

                                          return typeof(Book).GetProperties()
                                          .SelectMany(prop => prop.GetCustomAttributes())
                                          .OfType<AuthorAttribute>()
                                          .ToDictionary(attribute => attribute.Name, attribute => attribute.Name);







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Jun 10 '16 at 12:39









                                          deedee

                                          10.7k32445




                                          10.7k32445





















                                              2














                                              Necromancing.

                                              For those that still have to maintain .NET 2.0, or those that want to do it without LINQ:



                                              public static object GetAttribute(System.Reflection.MemberInfo mi, System.Type t)
                                              objs.Length < 1)
                                              return null;

                                              return objs[0];




                                              public static T GetAttribute<T>(System.Reflection.MemberInfo mi)

                                              return (T)GetAttribute(mi, typeof(T));



                                              public delegate TResult GetValue_t<in T, out TResult>(T arg1);

                                              public static TValue GetAttributValue<TAttribute, TValue>(System.Reflection.MemberInfo mi, GetValue_t<TAttribute, TValue> value) where TAttribute : System.Attribute

                                              TAttribute objAtts = (TAttribute)mi.GetCustomAttributes(typeof(TAttribute), true);
                                              TAttribute att = (objAtts == null


                                              Example usage:



                                              System.Reflection.FieldInfo fi = t.GetField("PrintBackground");
                                              wkHtmlOptionNameAttribute att = GetAttribute<wkHtmlOptionNameAttribute>(fi);
                                              string name = GetAttributValue<wkHtmlOptionNameAttribute, string>(fi, delegate(wkHtmlOptionNameAttribute a) return a.Name;);


                                              or simply



                                              string aname = GetAttributValue<wkHtmlOptionNameAttribute, string>(fi, a => a.Name );





                                              share|improve this answer





























                                                2














                                                Necromancing.

                                                For those that still have to maintain .NET 2.0, or those that want to do it without LINQ:



                                                public static object GetAttribute(System.Reflection.MemberInfo mi, System.Type t)
                                                objs.Length < 1)
                                                return null;

                                                return objs[0];




                                                public static T GetAttribute<T>(System.Reflection.MemberInfo mi)

                                                return (T)GetAttribute(mi, typeof(T));



                                                public delegate TResult GetValue_t<in T, out TResult>(T arg1);

                                                public static TValue GetAttributValue<TAttribute, TValue>(System.Reflection.MemberInfo mi, GetValue_t<TAttribute, TValue> value) where TAttribute : System.Attribute

                                                TAttribute objAtts = (TAttribute)mi.GetCustomAttributes(typeof(TAttribute), true);
                                                TAttribute att = (objAtts == null


                                                Example usage:



                                                System.Reflection.FieldInfo fi = t.GetField("PrintBackground");
                                                wkHtmlOptionNameAttribute att = GetAttribute<wkHtmlOptionNameAttribute>(fi);
                                                string name = GetAttributValue<wkHtmlOptionNameAttribute, string>(fi, delegate(wkHtmlOptionNameAttribute a) return a.Name;);


                                                or simply



                                                string aname = GetAttributValue<wkHtmlOptionNameAttribute, string>(fi, a => a.Name );





                                                share|improve this answer



























                                                  2












                                                  2








                                                  2







                                                  Necromancing.

                                                  For those that still have to maintain .NET 2.0, or those that want to do it without LINQ:



                                                  public static object GetAttribute(System.Reflection.MemberInfo mi, System.Type t)
                                                  objs.Length < 1)
                                                  return null;

                                                  return objs[0];




                                                  public static T GetAttribute<T>(System.Reflection.MemberInfo mi)

                                                  return (T)GetAttribute(mi, typeof(T));



                                                  public delegate TResult GetValue_t<in T, out TResult>(T arg1);

                                                  public static TValue GetAttributValue<TAttribute, TValue>(System.Reflection.MemberInfo mi, GetValue_t<TAttribute, TValue> value) where TAttribute : System.Attribute

                                                  TAttribute objAtts = (TAttribute)mi.GetCustomAttributes(typeof(TAttribute), true);
                                                  TAttribute att = (objAtts == null


                                                  Example usage:



                                                  System.Reflection.FieldInfo fi = t.GetField("PrintBackground");
                                                  wkHtmlOptionNameAttribute att = GetAttribute<wkHtmlOptionNameAttribute>(fi);
                                                  string name = GetAttributValue<wkHtmlOptionNameAttribute, string>(fi, delegate(wkHtmlOptionNameAttribute a) return a.Name;);


                                                  or simply



                                                  string aname = GetAttributValue<wkHtmlOptionNameAttribute, string>(fi, a => a.Name );





                                                  share|improve this answer















                                                  Necromancing.

                                                  For those that still have to maintain .NET 2.0, or those that want to do it without LINQ:



                                                  public static object GetAttribute(System.Reflection.MemberInfo mi, System.Type t)
                                                  objs.Length < 1)
                                                  return null;

                                                  return objs[0];




                                                  public static T GetAttribute<T>(System.Reflection.MemberInfo mi)

                                                  return (T)GetAttribute(mi, typeof(T));



                                                  public delegate TResult GetValue_t<in T, out TResult>(T arg1);

                                                  public static TValue GetAttributValue<TAttribute, TValue>(System.Reflection.MemberInfo mi, GetValue_t<TAttribute, TValue> value) where TAttribute : System.Attribute

                                                  TAttribute objAtts = (TAttribute)mi.GetCustomAttributes(typeof(TAttribute), true);
                                                  TAttribute att = (objAtts == null


                                                  Example usage:



                                                  System.Reflection.FieldInfo fi = t.GetField("PrintBackground");
                                                  wkHtmlOptionNameAttribute att = GetAttribute<wkHtmlOptionNameAttribute>(fi);
                                                  string name = GetAttributValue<wkHtmlOptionNameAttribute, string>(fi, delegate(wkHtmlOptionNameAttribute a) return a.Name;);


                                                  or simply



                                                  string aname = GetAttributValue<wkHtmlOptionNameAttribute, string>(fi, a => a.Name );






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Jun 12 '17 at 8:31

























                                                  answered Jun 12 '17 at 8:26









                                                  Stefan SteigerStefan Steiger

                                                  46k56271360




                                                  46k56271360





















                                                      1














                                                      public static class PropertyInfoExtensions

                                                      public static TValue GetAttributValue<TAttribute, TValue>(this PropertyInfo prop, Func<TAttribute, TValue> value) where TAttribute : Attribute

                                                      var att = prop.GetCustomAttributes(
                                                      typeof(TAttribute), true
                                                      ).FirstOrDefault() as TAttribute;
                                                      if (att != null)

                                                      return value(att);

                                                      return default(TValue);




                                                      Usage:



                                                       //get class properties with attribute [AuthorAttribute]
                                                      var props = typeof(Book).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(AuthorAttribute)));
                                                      foreach (var prop in props)

                                                      string value = prop.GetAttributValue((AuthorAttribute a) => a.Name);



                                                      or:



                                                       //get class properties with attribute [AuthorAttribute]
                                                      var props = typeof(Book).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(AuthorAttribute)));
                                                      IList<string> values = props.Select(prop => prop.GetAttributValue((AuthorAttribute a) => a.Name)).Where(attr => attr != null).ToList();





                                                      share|improve this answer



























                                                        1














                                                        public static class PropertyInfoExtensions

                                                        public static TValue GetAttributValue<TAttribute, TValue>(this PropertyInfo prop, Func<TAttribute, TValue> value) where TAttribute : Attribute

                                                        var att = prop.GetCustomAttributes(
                                                        typeof(TAttribute), true
                                                        ).FirstOrDefault() as TAttribute;
                                                        if (att != null)

                                                        return value(att);

                                                        return default(TValue);




                                                        Usage:



                                                         //get class properties with attribute [AuthorAttribute]
                                                        var props = typeof(Book).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(AuthorAttribute)));
                                                        foreach (var prop in props)

                                                        string value = prop.GetAttributValue((AuthorAttribute a) => a.Name);



                                                        or:



                                                         //get class properties with attribute [AuthorAttribute]
                                                        var props = typeof(Book).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(AuthorAttribute)));
                                                        IList<string> values = props.Select(prop => prop.GetAttributValue((AuthorAttribute a) => a.Name)).Where(attr => attr != null).ToList();





                                                        share|improve this answer

























                                                          1












                                                          1








                                                          1







                                                          public static class PropertyInfoExtensions

                                                          public static TValue GetAttributValue<TAttribute, TValue>(this PropertyInfo prop, Func<TAttribute, TValue> value) where TAttribute : Attribute

                                                          var att = prop.GetCustomAttributes(
                                                          typeof(TAttribute), true
                                                          ).FirstOrDefault() as TAttribute;
                                                          if (att != null)

                                                          return value(att);

                                                          return default(TValue);




                                                          Usage:



                                                           //get class properties with attribute [AuthorAttribute]
                                                          var props = typeof(Book).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(AuthorAttribute)));
                                                          foreach (var prop in props)

                                                          string value = prop.GetAttributValue((AuthorAttribute a) => a.Name);



                                                          or:



                                                           //get class properties with attribute [AuthorAttribute]
                                                          var props = typeof(Book).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(AuthorAttribute)));
                                                          IList<string> values = props.Select(prop => prop.GetAttributValue((AuthorAttribute a) => a.Name)).Where(attr => attr != null).ToList();





                                                          share|improve this answer













                                                          public static class PropertyInfoExtensions

                                                          public static TValue GetAttributValue<TAttribute, TValue>(this PropertyInfo prop, Func<TAttribute, TValue> value) where TAttribute : Attribute

                                                          var att = prop.GetCustomAttributes(
                                                          typeof(TAttribute), true
                                                          ).FirstOrDefault() as TAttribute;
                                                          if (att != null)

                                                          return value(att);

                                                          return default(TValue);




                                                          Usage:



                                                           //get class properties with attribute [AuthorAttribute]
                                                          var props = typeof(Book).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(AuthorAttribute)));
                                                          foreach (var prop in props)

                                                          string value = prop.GetAttributValue((AuthorAttribute a) => a.Name);



                                                          or:



                                                           //get class properties with attribute [AuthorAttribute]
                                                          var props = typeof(Book).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(AuthorAttribute)));
                                                          IList<string> values = props.Select(prop => prop.GetAttributValue((AuthorAttribute a) => a.Name)).Where(attr => attr != null).ToList();






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Nov 12 '15 at 15:32









                                                          VictorVictor

                                                          112




                                                          112





















                                                              0














                                                              foreach (var p in model.GetType().GetProperties())

                                                              var valueOfDisplay =
                                                              p.GetCustomAttributesData()
                                                              .Any(a => a.AttributeType.Name == "DisplayNameAttribute") ?
                                                              p.GetCustomAttribute<DisplayNameAttribute>().DisplayName :
                                                              p.Name;



                                                              In this example I used DisplayName instead of Author because it has a field named 'DisplayName' to be shown with a value.






                                                              share|improve this answer





























                                                                0














                                                                foreach (var p in model.GetType().GetProperties())

                                                                var valueOfDisplay =
                                                                p.GetCustomAttributesData()
                                                                .Any(a => a.AttributeType.Name == "DisplayNameAttribute") ?
                                                                p.GetCustomAttribute<DisplayNameAttribute>().DisplayName :
                                                                p.Name;



                                                                In this example I used DisplayName instead of Author because it has a field named 'DisplayName' to be shown with a value.






                                                                share|improve this answer



























                                                                  0












                                                                  0








                                                                  0







                                                                  foreach (var p in model.GetType().GetProperties())

                                                                  var valueOfDisplay =
                                                                  p.GetCustomAttributesData()
                                                                  .Any(a => a.AttributeType.Name == "DisplayNameAttribute") ?
                                                                  p.GetCustomAttribute<DisplayNameAttribute>().DisplayName :
                                                                  p.Name;



                                                                  In this example I used DisplayName instead of Author because it has a field named 'DisplayName' to be shown with a value.






                                                                  share|improve this answer















                                                                  foreach (var p in model.GetType().GetProperties())

                                                                  var valueOfDisplay =
                                                                  p.GetCustomAttributesData()
                                                                  .Any(a => a.AttributeType.Name == "DisplayNameAttribute") ?
                                                                  p.GetCustomAttribute<DisplayNameAttribute>().DisplayName :
                                                                  p.Name;



                                                                  In this example I used DisplayName instead of Author because it has a field named 'DisplayName' to be shown with a value.







                                                                  share|improve this answer














                                                                  share|improve this answer



                                                                  share|improve this answer








                                                                  edited Feb 10 '17 at 13:21









                                                                  Andrea

                                                                  85411227




                                                                  85411227










                                                                  answered Feb 3 '17 at 20:24









                                                                  petrosmmpetrosmm

                                                                  118313




                                                                  118313





















                                                                      0














                                                                      Here are some static methods you can use to get the MaxLength, or any other attribute.



                                                                      using System;
                                                                      using System.Linq;
                                                                      using System.Reflection;
                                                                      using System.ComponentModel.DataAnnotations;
                                                                      using System.Linq.Expressions;

                                                                      public static class AttributeHelpers

                                                                      public static Int32 GetMaxLength<T>(Expression<Func<T,string>> propertyExpression)
                                                                      return GetPropertyAttributeValue<T,string,MaxLengthAttribute,Int32>(propertyExpression,attr => attr.Length);


                                                                      //Optional Extension method
                                                                      public static Int32 GetMaxLength<T>(this T instance,Expression<Func<T,string>> propertyExpression)
                                                                      return GetMaxLength<T>(propertyExpression);



                                                                      //Required generic method to get any property attribute from any class
                                                                      public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>(Expression<Func<T,TOut>> propertyExpression,Func<TAttribute,TValue> valueSelector) where TAttribute : Attribute
                                                                      var expression = (MemberExpression)propertyExpression.Body;
                                                                      var propertyInfo = (PropertyInfo)expression.Member;
                                                                      var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute),true).FirstOrDefault() as TAttribute;

                                                                      if (attr==null)
                                                                      throw new MissingMemberException(typeof(T).Name+"."+propertyInfo.Name,typeof(TAttribute).Name);


                                                                      return valueSelector(attr);





                                                                      Using the static method...



                                                                      var length = AttributeHelpers.GetMaxLength<Player>(x => x.PlayerName);


                                                                      Or using the optional extension method on an instance...



                                                                      var player = new Player();
                                                                      var length = player.GetMaxLength(x => x.PlayerName);


                                                                      Or using the full static method for any other attribute (StringLength for example)...



                                                                      var length = AttributeHelpers.GetPropertyAttributeValue<Player,string,StringLengthAttribute,Int32>(prop => prop.PlayerName,attr => attr.MaximumLength);


                                                                      Inspired by the Mikael Engver's answer.






                                                                      share|improve this answer





























                                                                        0














                                                                        Here are some static methods you can use to get the MaxLength, or any other attribute.



                                                                        using System;
                                                                        using System.Linq;
                                                                        using System.Reflection;
                                                                        using System.ComponentModel.DataAnnotations;
                                                                        using System.Linq.Expressions;

                                                                        public static class AttributeHelpers

                                                                        public static Int32 GetMaxLength<T>(Expression<Func<T,string>> propertyExpression)
                                                                        return GetPropertyAttributeValue<T,string,MaxLengthAttribute,Int32>(propertyExpression,attr => attr.Length);


                                                                        //Optional Extension method
                                                                        public static Int32 GetMaxLength<T>(this T instance,Expression<Func<T,string>> propertyExpression)
                                                                        return GetMaxLength<T>(propertyExpression);



                                                                        //Required generic method to get any property attribute from any class
                                                                        public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>(Expression<Func<T,TOut>> propertyExpression,Func<TAttribute,TValue> valueSelector) where TAttribute : Attribute
                                                                        var expression = (MemberExpression)propertyExpression.Body;
                                                                        var propertyInfo = (PropertyInfo)expression.Member;
                                                                        var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute),true).FirstOrDefault() as TAttribute;

                                                                        if (attr==null)
                                                                        throw new MissingMemberException(typeof(T).Name+"."+propertyInfo.Name,typeof(TAttribute).Name);


                                                                        return valueSelector(attr);





                                                                        Using the static method...



                                                                        var length = AttributeHelpers.GetMaxLength<Player>(x => x.PlayerName);


                                                                        Or using the optional extension method on an instance...



                                                                        var player = new Player();
                                                                        var length = player.GetMaxLength(x => x.PlayerName);


                                                                        Or using the full static method for any other attribute (StringLength for example)...



                                                                        var length = AttributeHelpers.GetPropertyAttributeValue<Player,string,StringLengthAttribute,Int32>(prop => prop.PlayerName,attr => attr.MaximumLength);


                                                                        Inspired by the Mikael Engver's answer.






                                                                        share|improve this answer



























                                                                          0












                                                                          0








                                                                          0







                                                                          Here are some static methods you can use to get the MaxLength, or any other attribute.



                                                                          using System;
                                                                          using System.Linq;
                                                                          using System.Reflection;
                                                                          using System.ComponentModel.DataAnnotations;
                                                                          using System.Linq.Expressions;

                                                                          public static class AttributeHelpers

                                                                          public static Int32 GetMaxLength<T>(Expression<Func<T,string>> propertyExpression)
                                                                          return GetPropertyAttributeValue<T,string,MaxLengthAttribute,Int32>(propertyExpression,attr => attr.Length);


                                                                          //Optional Extension method
                                                                          public static Int32 GetMaxLength<T>(this T instance,Expression<Func<T,string>> propertyExpression)
                                                                          return GetMaxLength<T>(propertyExpression);



                                                                          //Required generic method to get any property attribute from any class
                                                                          public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>(Expression<Func<T,TOut>> propertyExpression,Func<TAttribute,TValue> valueSelector) where TAttribute : Attribute
                                                                          var expression = (MemberExpression)propertyExpression.Body;
                                                                          var propertyInfo = (PropertyInfo)expression.Member;
                                                                          var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute),true).FirstOrDefault() as TAttribute;

                                                                          if (attr==null)
                                                                          throw new MissingMemberException(typeof(T).Name+"."+propertyInfo.Name,typeof(TAttribute).Name);


                                                                          return valueSelector(attr);





                                                                          Using the static method...



                                                                          var length = AttributeHelpers.GetMaxLength<Player>(x => x.PlayerName);


                                                                          Or using the optional extension method on an instance...



                                                                          var player = new Player();
                                                                          var length = player.GetMaxLength(x => x.PlayerName);


                                                                          Or using the full static method for any other attribute (StringLength for example)...



                                                                          var length = AttributeHelpers.GetPropertyAttributeValue<Player,string,StringLengthAttribute,Int32>(prop => prop.PlayerName,attr => attr.MaximumLength);


                                                                          Inspired by the Mikael Engver's answer.






                                                                          share|improve this answer















                                                                          Here are some static methods you can use to get the MaxLength, or any other attribute.



                                                                          using System;
                                                                          using System.Linq;
                                                                          using System.Reflection;
                                                                          using System.ComponentModel.DataAnnotations;
                                                                          using System.Linq.Expressions;

                                                                          public static class AttributeHelpers

                                                                          public static Int32 GetMaxLength<T>(Expression<Func<T,string>> propertyExpression)
                                                                          return GetPropertyAttributeValue<T,string,MaxLengthAttribute,Int32>(propertyExpression,attr => attr.Length);


                                                                          //Optional Extension method
                                                                          public static Int32 GetMaxLength<T>(this T instance,Expression<Func<T,string>> propertyExpression)
                                                                          return GetMaxLength<T>(propertyExpression);



                                                                          //Required generic method to get any property attribute from any class
                                                                          public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>(Expression<Func<T,TOut>> propertyExpression,Func<TAttribute,TValue> valueSelector) where TAttribute : Attribute
                                                                          var expression = (MemberExpression)propertyExpression.Body;
                                                                          var propertyInfo = (PropertyInfo)expression.Member;
                                                                          var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute),true).FirstOrDefault() as TAttribute;

                                                                          if (attr==null)
                                                                          throw new MissingMemberException(typeof(T).Name+"."+propertyInfo.Name,typeof(TAttribute).Name);


                                                                          return valueSelector(attr);





                                                                          Using the static method...



                                                                          var length = AttributeHelpers.GetMaxLength<Player>(x => x.PlayerName);


                                                                          Or using the optional extension method on an instance...



                                                                          var player = new Player();
                                                                          var length = player.GetMaxLength(x => x.PlayerName);


                                                                          Or using the full static method for any other attribute (StringLength for example)...



                                                                          var length = AttributeHelpers.GetPropertyAttributeValue<Player,string,StringLengthAttribute,Int32>(prop => prop.PlayerName,attr => attr.MaximumLength);


                                                                          Inspired by the Mikael Engver's answer.







                                                                          share|improve this answer














                                                                          share|improve this answer



                                                                          share|improve this answer








                                                                          edited Mar 28 '17 at 19:10

























                                                                          answered Mar 28 '17 at 17:37









                                                                          Carter MedlinCarter Medlin

                                                                          8,69944661




                                                                          8,69944661





















                                                                              0














                                                                              to get attribute from enum, i'm using :



                                                                               public enum ExceptionCodes

                                                                              [ExceptionCode(1000)]
                                                                              InternalError,


                                                                              public static (int code, string message) Translate(ExceptionCodes code)

                                                                              return code.GetType()
                                                                              .GetField(Enum.GetName(typeof(ExceptionCodes), code))
                                                                              .GetCustomAttributes(false).Where((attr) =>

                                                                              return (attr is ExceptionCodeAttribute);
                                                                              ).Select(customAttr =>

                                                                              var attr = (customAttr as ExceptionCodeAttribute);
                                                                              return (attr.Code, attr.FriendlyMessage);
                                                                              ).FirstOrDefault();



                                                                              // Using



                                                                               var _message = Translate(code);





                                                                              share|improve this answer



























                                                                                0














                                                                                to get attribute from enum, i'm using :



                                                                                 public enum ExceptionCodes

                                                                                [ExceptionCode(1000)]
                                                                                InternalError,


                                                                                public static (int code, string message) Translate(ExceptionCodes code)

                                                                                return code.GetType()
                                                                                .GetField(Enum.GetName(typeof(ExceptionCodes), code))
                                                                                .GetCustomAttributes(false).Where((attr) =>

                                                                                return (attr is ExceptionCodeAttribute);
                                                                                ).Select(customAttr =>

                                                                                var attr = (customAttr as ExceptionCodeAttribute);
                                                                                return (attr.Code, attr.FriendlyMessage);
                                                                                ).FirstOrDefault();



                                                                                // Using



                                                                                 var _message = Translate(code);





                                                                                share|improve this answer

























                                                                                  0












                                                                                  0








                                                                                  0







                                                                                  to get attribute from enum, i'm using :



                                                                                   public enum ExceptionCodes

                                                                                  [ExceptionCode(1000)]
                                                                                  InternalError,


                                                                                  public static (int code, string message) Translate(ExceptionCodes code)

                                                                                  return code.GetType()
                                                                                  .GetField(Enum.GetName(typeof(ExceptionCodes), code))
                                                                                  .GetCustomAttributes(false).Where((attr) =>

                                                                                  return (attr is ExceptionCodeAttribute);
                                                                                  ).Select(customAttr =>

                                                                                  var attr = (customAttr as ExceptionCodeAttribute);
                                                                                  return (attr.Code, attr.FriendlyMessage);
                                                                                  ).FirstOrDefault();



                                                                                  // Using



                                                                                   var _message = Translate(code);





                                                                                  share|improve this answer













                                                                                  to get attribute from enum, i'm using :



                                                                                   public enum ExceptionCodes

                                                                                  [ExceptionCode(1000)]
                                                                                  InternalError,


                                                                                  public static (int code, string message) Translate(ExceptionCodes code)

                                                                                  return code.GetType()
                                                                                  .GetField(Enum.GetName(typeof(ExceptionCodes), code))
                                                                                  .GetCustomAttributes(false).Where((attr) =>

                                                                                  return (attr is ExceptionCodeAttribute);
                                                                                  ).Select(customAttr =>

                                                                                  var attr = (customAttr as ExceptionCodeAttribute);
                                                                                  return (attr.Code, attr.FriendlyMessage);
                                                                                  ).FirstOrDefault();



                                                                                  // Using



                                                                                   var _message = Translate(code);






                                                                                  share|improve this answer












                                                                                  share|improve this answer



                                                                                  share|improve this answer










                                                                                  answered Jan 9 '18 at 8:15









                                                                                  Mohamed.AbdoMohamed.Abdo

                                                                                  854810




                                                                                  854810





















                                                                                      0














                                                                                      Just looking for the right place to put this piece of code.



                                                                                      let's say you have the following property:



                                                                                      [Display(Name = "Solar Radiation (Average)", ShortName = "SolarRadiationAvg")]
                                                                                      public int SolarRadiationAvgSensorId get; set;


                                                                                      And you want to get the ShortName value. You can do:



                                                                                      ((DisplayAttribute)(typeof(SensorsModel).GetProperty(SolarRadiationAvgSensorId).GetCustomAttribute(typeof(DisplayAttribute)))).ShortName;


                                                                                      Or to make it general:



                                                                                      internal static string GetPropertyAttributeShortName(string propertyName)

                                                                                      return ((DisplayAttribute)(typeof(SensorsModel).GetProperty(propertyName).GetCustomAttribute(typeof(DisplayAttribute)))).ShortName;






                                                                                      share|improve this answer



























                                                                                        0














                                                                                        Just looking for the right place to put this piece of code.



                                                                                        let's say you have the following property:



                                                                                        [Display(Name = "Solar Radiation (Average)", ShortName = "SolarRadiationAvg")]
                                                                                        public int SolarRadiationAvgSensorId get; set;


                                                                                        And you want to get the ShortName value. You can do:



                                                                                        ((DisplayAttribute)(typeof(SensorsModel).GetProperty(SolarRadiationAvgSensorId).GetCustomAttribute(typeof(DisplayAttribute)))).ShortName;


                                                                                        Or to make it general:



                                                                                        internal static string GetPropertyAttributeShortName(string propertyName)

                                                                                        return ((DisplayAttribute)(typeof(SensorsModel).GetProperty(propertyName).GetCustomAttribute(typeof(DisplayAttribute)))).ShortName;






                                                                                        share|improve this answer

























                                                                                          0












                                                                                          0








                                                                                          0







                                                                                          Just looking for the right place to put this piece of code.



                                                                                          let's say you have the following property:



                                                                                          [Display(Name = "Solar Radiation (Average)", ShortName = "SolarRadiationAvg")]
                                                                                          public int SolarRadiationAvgSensorId get; set;


                                                                                          And you want to get the ShortName value. You can do:



                                                                                          ((DisplayAttribute)(typeof(SensorsModel).GetProperty(SolarRadiationAvgSensorId).GetCustomAttribute(typeof(DisplayAttribute)))).ShortName;


                                                                                          Or to make it general:



                                                                                          internal static string GetPropertyAttributeShortName(string propertyName)

                                                                                          return ((DisplayAttribute)(typeof(SensorsModel).GetProperty(propertyName).GetCustomAttribute(typeof(DisplayAttribute)))).ShortName;






                                                                                          share|improve this answer













                                                                                          Just looking for the right place to put this piece of code.



                                                                                          let's say you have the following property:



                                                                                          [Display(Name = "Solar Radiation (Average)", ShortName = "SolarRadiationAvg")]
                                                                                          public int SolarRadiationAvgSensorId get; set;


                                                                                          And you want to get the ShortName value. You can do:



                                                                                          ((DisplayAttribute)(typeof(SensorsModel).GetProperty(SolarRadiationAvgSensorId).GetCustomAttribute(typeof(DisplayAttribute)))).ShortName;


                                                                                          Or to make it general:



                                                                                          internal static string GetPropertyAttributeShortName(string propertyName)

                                                                                          return ((DisplayAttribute)(typeof(SensorsModel).GetProperty(propertyName).GetCustomAttribute(typeof(DisplayAttribute)))).ShortName;







                                                                                          share|improve this answer












                                                                                          share|improve this answer



                                                                                          share|improve this answer










                                                                                          answered Jun 25 '18 at 0:14









                                                                                          AsafAsaf

                                                                                          34046




                                                                                          34046





















                                                                                              0














                                                                                              While the above most upvoted answers definitely work, I'd suggest using a slightly different approach in some cases.



                                                                                              If your class has multiple properties with always the same attribute and you want to get those attributes sorted into a dictionary, here is how:



                                                                                              var dict = typeof(Book).GetProperties().ToDictionary(p => p.Name, p => p.GetCustomAttributes(typeof(AuthorName), false).Select(a => (AuthorName)a).FirstOrDefault());


                                                                                              This still uses cast but ensures that the cast will always work as you will only get the custom attributes of the type "AuthorName".
                                                                                              If you had multiple Attributes above answers would get a cast exception.






                                                                                              share|improve this answer



























                                                                                                0














                                                                                                While the above most upvoted answers definitely work, I'd suggest using a slightly different approach in some cases.



                                                                                                If your class has multiple properties with always the same attribute and you want to get those attributes sorted into a dictionary, here is how:



                                                                                                var dict = typeof(Book).GetProperties().ToDictionary(p => p.Name, p => p.GetCustomAttributes(typeof(AuthorName), false).Select(a => (AuthorName)a).FirstOrDefault());


                                                                                                This still uses cast but ensures that the cast will always work as you will only get the custom attributes of the type "AuthorName".
                                                                                                If you had multiple Attributes above answers would get a cast exception.






                                                                                                share|improve this answer

























                                                                                                  0












                                                                                                  0








                                                                                                  0







                                                                                                  While the above most upvoted answers definitely work, I'd suggest using a slightly different approach in some cases.



                                                                                                  If your class has multiple properties with always the same attribute and you want to get those attributes sorted into a dictionary, here is how:



                                                                                                  var dict = typeof(Book).GetProperties().ToDictionary(p => p.Name, p => p.GetCustomAttributes(typeof(AuthorName), false).Select(a => (AuthorName)a).FirstOrDefault());


                                                                                                  This still uses cast but ensures that the cast will always work as you will only get the custom attributes of the type "AuthorName".
                                                                                                  If you had multiple Attributes above answers would get a cast exception.






                                                                                                  share|improve this answer













                                                                                                  While the above most upvoted answers definitely work, I'd suggest using a slightly different approach in some cases.



                                                                                                  If your class has multiple properties with always the same attribute and you want to get those attributes sorted into a dictionary, here is how:



                                                                                                  var dict = typeof(Book).GetProperties().ToDictionary(p => p.Name, p => p.GetCustomAttributes(typeof(AuthorName), false).Select(a => (AuthorName)a).FirstOrDefault());


                                                                                                  This still uses cast but ensures that the cast will always work as you will only get the custom attributes of the type "AuthorName".
                                                                                                  If you had multiple Attributes above answers would get a cast exception.







                                                                                                  share|improve this answer












                                                                                                  share|improve this answer



                                                                                                  share|improve this answer










                                                                                                  answered Feb 5 at 11:14









                                                                                                  Mirko BrandtMirko Brandt

                                                                                                  11




                                                                                                  11



























                                                                                                      draft saved

                                                                                                      draft discarded
















































                                                                                                      Thanks for contributing an answer to Stack Overflow!


                                                                                                      • Please be sure to answer the question. Provide details and share your research!

                                                                                                      But avoid


                                                                                                      • Asking for help, clarification, or responding to other answers.

                                                                                                      • Making statements based on opinion; back them up with references or personal experience.

                                                                                                      To learn more, see our tips on writing great answers.




                                                                                                      draft saved


                                                                                                      draft discarded














                                                                                                      StackExchange.ready(
                                                                                                      function ()
                                                                                                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6637679%2freflection-get-attribute-name-and-value-on-property%23new-answer', 'question_page');

                                                                                                      );

                                                                                                      Post as a guest















                                                                                                      Required, but never shown





















































                                                                                                      Required, but never shown














                                                                                                      Required, but never shown












                                                                                                      Required, but never shown







                                                                                                      Required, but never shown

































                                                                                                      Required, but never shown














                                                                                                      Required, but never shown












                                                                                                      Required, but never shown







                                                                                                      Required, but never shown







                                                                                                      Popular posts from this blog

                                                                                                      Use pre created SQLite database for Android project in kotlin

                                                                                                      Darth Vader #20

                                                                                                      Ondo