34

I've been working with Reflections and wanted to get all the attributes declared for a property. There are two properties under PropertInfo class which are CustomAttributes and Attributes.

According to the MSDN, they are explained as follows:

Attributes:

This property represents the attributes associated with a member. All members have a set of attributes that are defined in relation to the specific type of member. The property attributes let the user know if this property is the default property, a SpecialName property, and so on.

Note: The code sample given in the PropertyInfo.Attributes page doesn't even work.

Custom Attributes:

An array that contains all the custom attributes applied to this member, or an array with zero elements if no attributes are defined.

However, when I run this code for them, Attributes returns nothing while CustomAttributes returns Required.

void Main()
{
    var attributes = typeof(Myproperty).GetProperty("Caption").CustomAttributes;
    //var attributes = typeof(Myproperty).GetProperty("Caption").Attributes;
    attributes.Dump(); //Dump is a LinqPad method which dumps everything to the outpu window
}

public class Myproperty
{
    private string caption = "Default caption";

    [Required]
    public string Caption
    {
        get{return caption;}
        set {if(caption!=value) {caption = value;}
        }
    }
}
4
  • 1
    Basically they're slightly different meanings of the word "attribute" here. It sounds like you do want CustomAttributes.
    – Jon Skeet
    Jul 30, 2013 at 18:04
  • I've figured that what I wanted is CustomAttributes but can you please explain what the difference is? IMO it seems it doesn't do what its name implies.
    – Tarik
    Jul 30, 2013 at 18:05
  • 1
    Basically, see the answer from Hans. They're very different things. Look at MethodInfo.Attributes for an example which may make more sense to you - it's more like the modifiers that can be applied to a property / method / etc.
    – Jon Skeet
    Jul 30, 2013 at 18:11
  • See static methods of System.Attribute if you want to discover even inherited attributes.
    – Palec
    Jul 4, 2019 at 16:36

1 Answer 1

50

PropertyInfo.Attributes doesn't have anything to do with the Attribute class. Check the PropertyAttributes enumeration for values you may encounter. These are CLR implementation details that have no obvious connection to C# code. Yes, that was an unfortunate naming choice.

To find attributes like your [Required] attribute you must use the CustomAttributes property.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.