Search code examples
.netcustom-attributestypedescriptor

.Net: How to I get Custom Attributes using TypeDescriptor.GetProperties?


I have created my own attribute to decorate my object.

 [AttributeUsage(AttributeTargets.All)]
    public class MyCustomAttribute : System.Attribute { }

When I try to use TypeDescriptor.GetProperties passing in my custom attribute it doesn't return anything even though the type is decorated with the attribute.

  var props = TypeDescriptor.GetProperties(
              type, 
              new[] { new Attributes.FlatLoopValueInjection()});

How do I get TypeDescriptor.GetProperties to recognize my custom types?


Solution

  • The Type.GetProperties(type, Attributes[]) method returns only the collection of properties for a specified type of component using a specified array of attributes as a filter.
    Are you sure target type has a properties marked with your custom attributes, like this?

    //...
        var props = TypeDescriptor.GetProperties(typeof(Person), new Attribute[] { new NoteAttribute() });
        PropertyDescriptor nameProperty = props["Name"];
    }
    //...
    class Person {
        [Note]
        public string Name { get; set; }
    }
    //...
    class NoteAttribute : Attribute {
    /* implementation */
    }