O'Reilly logo

C# Essentials by Peter Drayton, Ben Albahari, Brad Merrill

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required