Home   Cover Cover Cover Cover


Example "Attributes"

With the CLR it is possible to make certain characteristics of program elements visible in the metadata by applying attributes to them in the source code. Other programs and tools can then access and evaluate these attributes at runtime.
In the example we define a class OurBook and mark it as serializable with the System.SerializableAttribute from the .NET class library. The class also contains a field ourPrice with the custom attribute TooLowAttribute.

using System;

class OurBook {

  int ourPrice;


class TooLowAttribute : Attribute { }

With the IL disassembler (ildasm.exe) we can not only look at the generated CIL code, but also at the metadata of the class OurBook and its components.

Here we see that for some attributes from the class library the CIL has reserved keywords (serializable), while custom attibutes are usually provided as calls to the corresponding constructor (.ctor) after the keyword .custom.