Search code examples
c#attributestypedescriptor

C#: What's the Difference Between TypeDescriptor.GetAttributes() and GetType() .GetCustomAttributes?


Take these two code things:

instance.GetType()
 .GetCustomAttributes(true)
 .Where(item => item is ValidationAttribute);

And

TypeDescriptor.GetAttributes(instance)
 .OfType<ValidationAttribute>();

If the class looks like:

[RequiredIfOtherPropertyIsNotEmpty("State", "City", ErrorMessage = ErrorDescription.CreateAccount_CityRequiredWithState)]
[RequiredIfOtherPropertyIsNotEmpty("State", "Address1", ErrorMessage = ErrorDescription.CreateAccount_Address1RequiredWithState)]
public class ManagePostModel
{
   ...
}

Where RequiredIfOtherPropertyIsNotEmpty is a ValidationAttribute and has AllowMultiple = true.

The first one returns two attributes, the second returns one.

What's the difference that would cause this?


Solution

  • From the MSDN page on TypeDescriptor.GetAttributes:

    In order to return multiple instances of an AttributeUsageAttribute.AllowMultiple attribute from the AttributeCollection, your attribute must override the Attribute.TypeId property.

    To answer the general question "what's the difference?": the values returned by TypeDescriptor can be extended at runtime, whereas those in Type cannot. The MSDN page I linked to explains more.

    If you don't need this kind of runtime extension, and the way TypeDescriptor handles multiple attributes is a problem, you're probably better off with Type.GetCustomAttributes.