Search code examples
c#reflectionattributesgetcustomattributes

Custom Attributes such as Displayname not listed with GetCustomAttribute


I have some code to define custom attributes and then to read in the code, it fails to work. To try and fix the problem I have gone back and tried to use DisplayName, however , I am still having the same issue GetCustomAttribute or GetCustomAttributes fails to list them. I have an example below.

I have a DisplayName Attribute set in a class, for example...

class TestClass
 {
        public TestClass() { }

        [DisplayName("this is a test")]
        public long testmethod{ get; set; }
 }

I then have some code to list the DisplayName Attribute for each method in the class above.

TestClass testClass = new TestClass();

   Type type = testClass.GetType();

            foreach (MethodInfo mInfo in type.GetMethods())
            {

            DisplayNameAttribute attr = (DisplayNameAttribute)Attribute.GetCustomAttribute(mInfo, typeof(DisplayNameAttribute));

                   if (attr !=null)
                    {
                        MessageBox.Show(attr.DisplayName);   

                    }


            }

The problem is that there are no DisplayName Attributes listed, Above code compiles, runs and doesn't display any messageboxes.

I have even tried to use a for each loop with GetCustomAttributes, listing all the attributes for each method again the DisplayName Attribute is never listed, however, I do get the compilation attributes and other such system attributes.

Anyone have any idea what I am doing wrong?

UPDATE- Many thanks to NerdFury for pointing out that I was using Methods and not Properties. Once changed every thing worked.


Solution

  • You are putting the attribute on a Property and not a Method. Try the following code:

    TestClass testClass = new TestClass();
    
       Type type = testClass.GetType();
    
       foreach (PropertyInfo pInfo in type.GetProperties())
       {
           DisplayNameAttribute attr = (DisplayNameAttribute)Attribute.GetCustomAttribute(pInfo, typeof(DisplayNameAttribute));
    
           if (attr !=null)
           {
               MessageBox.Show(attr.DisplayName);   
           }
       }