Custom Attributes

Types, members, modules, and assemblies all have associated metadata that is used by all the major CLR services, is considered an indivisible part of an application, and can be accessed via reflection (see the earlier Section 3.10).

A key characteristic of metadata is that it can be extended. You extend the metadata with custom attributes, which allow you to “decorate” a code element with additional information stored in the metadata associated with the element.

This additional information can then be retrieved at runtime and used to build services that work declaratively, which is the way that the CLR implements core features such as serialization and interception.

Language Support for Custom Attributes

Decorating an element with a custom attribute is known as specifying the custom attribute and is done by writing the name of the attribute enclosed in brackets ([]) immediately before the element declaration as follows:

[Serializable] public class Foo {...}

In this example, the Foo class is specified as serializable. This information is saved in the metadata for Foo, and affects the way the CLR treats an instance of this class.

A useful way to think about custom attributes is that they expand the built-in set of declarative constructs in the C# language such as public, private, and sealed.

Compiler Support for Custom Attributes

In reality, custom attributes are simply types derived from System.Attribute with language constructs for specifying them on an element (see ...

Get C# Essentials now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.