views:

40

answers:

3

If multiple attributes are applied to a member, e.g.

[Foo]
[Bar]
void Baz() { ... }

Then are any guarantees made by the CLR/.NET specifications as to what order they will be retrieved in when retrieved by reflection (e.g. Attribute.GetCustomAttributes)? The documentation for these methods does not make it explicit, and while it does seem to be the case that they are returned in the order they are applied, I don't want to rely on undocumented behaviour as that's just asking for trouble.

As for why this might be important, imagine the attributes are used to indicate that the method should have a series of interceptors, which should run in a specific order.

+1  A: 

Relying on ordering for this sort of thing is generally a bad idea. If the order is important, I would give the attribute a Priority property so that it can be made very explicit.

I don't know of any guarantees that they will be retrieved in the original order.

Jon Skeet
Yes, I agree. I'd given them an `AspectOrder` property to control this, but was just intrigued as to whether it was necessary to guarantee ordering as opposed to intention.
Greg Beech
+3  A: 

No from 17.2 Attribute specification it does not seems so.

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.

astander
Seems pretty conclusive - thanks. It's what I expected to be honest.
Greg Beech
+1  A: 

imo Attributes shouldn't have an order as they're not flow control constructs.

I guess you could add a priority property to the attribute and use that to determine the run order?

RSlaughter
gargh - beaten by Skeet, why do I bother? ;)
RSlaughter