reflection GetCustomAttributes

mp3909

Well-known member
Joined
Apr 22, 2018
Messages
61
Location
UK
Programming Experience
3-5
Comment in the code below says it all

C#:
using System;
using System.Reflection;

namespace Sample
{

    public class Valid : Attribute { }

    public class Customer
    {
        #region Properties
        public string firstname { get; set; }
        public string lastname { get; set; }
        #endregion
        
        [Valid]
        public void PrintFullName()
        {
            Console.WriteLine(this.firstname + " " + this.lastname);
        }

        public void PrintReverseName()
        {
            Console.WriteLine(this.lastname + " " + this.firstname);
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            foreach(Type t in Assembly.GetExecutingAssembly().GetTypes())
            {
                if(t.Name == "Customer")
                {
                    Type tt = Assembly.GetExecutingAssembly().GetType(t.FullName);

                    foreach (MethodInfo minfo in tt.GetMethods())
                    {
                        if(minfo.GetCustomAttributes() is Valid)
                        {
                            Console.WriteLine(minfo.Name);     //i thought here it would print out the method name PrintFullName but it doesn't
                        }
                    }
                }
            }
        }
    }
}
 
On line 40, GetCustomAttributes() returns an array of attributes. You still need to enumerate each on of those (or use one of the LINQ extension methods) to see which on is a Valid type.

Tangent to your problem, the convention is to name an attribute with the "Attribute" suffix, even though when you use the attribute, you can skip the suffix. So your Valid attribute should be named ValidAttribute.
 
As suggested by Skydiver and the name of the method, GetCustomAttributes returns (potentially) multiple attributes. You need to filter that result somehow. Under the circumstances, I would probably do this:
C#:
if(minfo.GetCustomAttributes().Any(a => a is Valid))
 
Back
Top Bottom