Saturday, November 26, 2011

C# Reflection and Custom Attributes

 public class Animal
    {
        [Required]//from System.ComponentModel.DataAnnotations;
        public string Name { get; set; }
    }

    public class CustomAttributes
    {
        static void FindCustomAttributes(string[] args)
        {
            Type type = typeof(Animal);
            PropertyInfo propertyInfo = type.GetProperty("Name");
            object[] attributes = propertyInfo.GetCustomAttributes(false);//this returns RequiredAttribute
            foreach (Attribute attribute in attributes)
            {
                Console.WriteLine(attribute.GetType().Name);
            }
        }
    }

No comments:

Post a Comment