Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ICustomAttributeProvider.GetCustomAttributes() return object[] instead of Attribute[]?

Why does ICustomAttributeProvider.GetCustomAttributes() return object[] instead of Attribute[]?

Is there any circumstance when using the ICustomAttributeProvider implementations from mscorlib and System assemblies will return objects that are not of type Attribute?

like image 367
smartcaveman Avatar asked Apr 28 '11 19:04

smartcaveman


2 Answers

The CLI spec (ECMA 335) Partition II, Clause 21 states in part:

While any user-defined type can be used as an attribute, CLS compliance requires that attributes will be instances of types whose base class is System.Attribute.

In other words, a language that is not CLS-compliant may allow you to specify attributes that do not derive from Attribute, so the GetCustomAttributes method is probably designed to allow such attributes to be consumed.

I'm pretty sure that no such non-CLS-compliant language exists, and .NET doesn't support it, but one can imagine that the designers of Reflection did not want to preclude the possibility in the future.

As for your second question, a quick inspection of the source code for System.Reflection shows that you always get an Attribute[] back. Since the returned objects are always Attribute[], you can safely cast them, but there's no guarantee that it will always work that way.

like image 142
Gabe Avatar answered Nov 15 '22 11:11

Gabe


By taking a quick look with Reflector, in every place it is used they perform a safe cast to Attribute[], so I guess it is safe for you to do the same.

like image 38
LazyOfT Avatar answered Nov 15 '22 13:11

LazyOfT