Question

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?

Was it helpful?

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 */
}

OTHER TIPS

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;}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top