Chapter 14. 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 Chapter 13).

A key characteristic of metadata is it can be extended. 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

Decorating an element with a custom attribute is known as specifying the custom attribute. This 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 they expand the built-in set of declarative constructs in the C# language, such as public, private, and sealed.

Get C# in a Nutshell, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.