0

Similar to Get properties in order of declaration using reflection I want to get attributes in the order of their declaration. Obviously, I'm referring to attributes having AllowMultiple set to true for their AttributeUsage.

I wonder if MemberInfo.GetCustomAttributes or Attribute.GetCustomAttributes guarantee any ordering (I haven't found anything in the MSDN).

Community
  • 1
  • 1
Dejan
  • 9,150
  • 8
  • 69
  • 117
  • I'm not sure anywhere defines order for these; you might also want to look at [GetCustomAttributesData](http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.getcustomattributesdata(v=vs.110).aspx), but that also isn't explicitly in declaration order – Marc Gravell Nov 13 '14 at 17:54

1 Answers1

1

The C# language specification says in 17.2 Attribute specification:

The order in which attributes are specified in such a list, and the order in which sections attached to the same program entity are arranged, is not significant.

For instance, the attribute specifications [A][B], [B][A], [A, B], and [B, A] are equivalent.

So the compiler can re-order them as it wants, and the methods for retrieving attributes can't guarantee to return them in any order.

You can of course use the workaround proposed in the question you link to, using [CallerLineNumber].

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272