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

5.3k views Asked by At

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?

2

There are 2 answers

0
DmitryG On BEST ANSWER

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 */
}
2
Jason On

updated to get property attribute

this code was copy and pasted from MSDN, which was the first result of the google search 'get customattribute reflection c#'

using System;

public class ExampleAttribute : Attribute
{
    private string stringVal;

    public ExampleAttribute()
    {
        stringVal = "This is the default string.";
    }

    public string StringValue
    {
        get { return stringVal; }
        set { stringVal = value; }
    }
}

[Example(StringValue="This is a string.")]
class Class1
{
    public static void Main()
    {
        PropertyInfo propertyInfo = typeof (Class1).GetProperties().Where(p => p.Name == "Foo").FirstOrDefault();
        foreach (object attrib in propertyInfo.GetCustomAttributes(true))
        {
            Console.WriteLine(attrib);
        }
    }

    [Example(StringValue = "property attribute")]
    public string Foo {get;set;}
}