richard
richard

Reputation: 12498

What is the compiler/CLR actually doing when attributes annotate a type/method/property?

When you annotate a type or method or property with an attribute, what is the compiler/CLR/etc. doing for you?

My guess is that it is "injecting" methods, properties, etc. into your class definitions (or maybe just into your object?, or?) and providing automatic behavior, sort of like how when you declare a delegate with the terse:

public delegate void MySuperSpecialDelegate(myAwesomeClass myAwesomeObject);

you then get some really great automatic behavior that is "injected" into the compiled code (CIL) for you.

So to reiterate the question, what is happening automatically "behind the scenes" when you use attributes?

Upvotes: 2

Views: 186

Answers (2)

user541686
user541686

Reputation: 210427

It depends on the attribute.

"Normal" attributes like CLSCompliantAttribute don't do anything at run-time (unless you try to read them, in which case they're instantiated); they're just metadata describing the data/code, that's sometimes used by the compiler and/or debugger to help the programmer.

"Special" attributes are, well, special. They can change flags in the code, cause the CLR behavior to change in some way, or cause some other observable change; it's attribute-dependent. (E.g. FieldOffsetAttribute can cause the field layout to change, which is obviously an observable run-time effect.)

An extreme example of change in behavior can be seen with the ProxyAttribute, in which case you can pretty much hijack the entire code for a class (even the constructor).

Other examples of such "special" attributes include InAttribute, OutAttribute, ThreadStaticAttribute, MTAThreadAttribute, TypeForwardedToAttribute (I think), ComImportAttribute, DllImportAttribute, etc, etc... there's actually quite a lot of them!

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062745

Absolutely nothing, with a few very specific examples:

  • PrincipalPermissionAttribute
  • MethodImplAttribute
  • etc

which have some very specific handling

Other than that, attributes are inert and only activated when explicitly using reflection.

There are a few that the compiler uses, though - ConditionalAttribute, SerializableAttribute, etc.

But to reiterate, in the general case and for the vast majority of attributes: nothing, nil, zip, nada nix and null.

Upvotes: 3

Related Questions