views:

129

answers:

3

Trying to find some verbose reference on the intricacies of Attributes. Any help would be appreciated.

At this point, I'd specifically like to know what time during runtime does an attribute constructor get ran?

  • If it's over a class
  • If it's over a property
  • If it's over a method

Thanks.

+2  A: 

The only thing that you can be sure is that it'll be called before is needed. It's not defined the exact time the constructor will be called.

Anyway, the behaviour is unespecified, so you shouldn't rely on whenever the constructur gets called by the current implementation.

AlbertEin
+1 - exactly my point in the comment to @Rex-M's answer.
Sunny
+3  A: 

The constructor is invoked when you call GetCustomAttributes() on the type or MemberInfo.

Rex M
Would you post a reference to this in the docs, please.
Sunny
@Sunny Run it through a debugger and see for yourself.
Rex M
Makes sense. To clarify: if I have an attribute on a class that get "constructed" when another class asks for GetCustomAttributes and the attribute GetCustomAttributes of its properties in its constructor, then it should all kind work.
divitiae
@Rex I could have run it through the debugger myself, but I figured stack overflow would be quicker, and it was :-P
divitiae
@divitiae correct.
Rex M
@divitiae of course! you asked and someone who's already done this answered you. But @Sunny doesn't seem to take my word for it :)
Rex M
@Rex-M: debug mode/code != release, so some behavior, displayed in a debugger is not a proof. I agree, that most probably you are right, but if it is not explicitly stated in the specification somewhere, it may change at any moment, and building a program on a "non-documented" feature is a bad idea.
Sunny
@Sunny I disagree, this app is probably not keeping the space shuttle in the air and this particular functionality is probably not critical to the app. Just because it *might* change doesn't mean we cant write something that works and move on. If it breaks in 2011, fix it then.
Rex M
+3  A: 

Reading the norm (17.3.2 in the C# 2.0 version) it's unspecified. Only the way to convert from the metatada to an instance is.

So you may need to test on different implementations, because if it isn't specified it's bound to be interpreted differently.

VirtualBlackFox
sort of like a static constructor?
divitiae
No, this one is actually specified.
VirtualBlackFox
... executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:An instance of the class is created.Any of the static members of the class are referenced.
VirtualBlackFox
@VirtualBlackFox a twofor! That clarifies that! +1
divitiae