CSharp - Get to know Attributes

What is Attribute

Attribute is metadata for source code.

Attribute Classes

An attribute is created by inheriting from the System.Attribute.

To add an attribute to a code element, mark the attribute's type name in square brackets, before the code element.

For example, the following attaches the ObsoleteAttribute to the Test class:

public class Test {}

By convention, all attribute types end in the word Attribute.

C# allows you to omit the suffix when attaching an attribute:

class Test {...}

ObsoleteAttribute is a type declared in the System namespace:

C# language includes a number of predefined attributes.

Attribute Targets

Normally the target of an attribute is the code element it immediately precedes.

To attach attributes to an assembly, specify the attribute's target.

The following code uses the CLSCompliant attribute to specify CLS compliance for an entire assembly:


Specifying Multiple Attributes

Multiple attributes can be specified for a single code element.

Each attribute can be listed

  • Within the same square brackets separated by a comma
  • In separate pairs of square brackets or
  • A combination of the two.

The following three examples are semantically identical:

[Serializable, Obsolete, CLSCompliant(false)]
public class Test {...}

[Serializable] [Obsolete] [CLSCompliant(false)]
public class Test {...}

[Serializable, Obsolete]
public class Test {...}

Named and Positional Attribute Parameters

Attributes may have parameters.

Suppose we have the following code which applies XmlElementAttribute to a class.

[XmlElement ("Customer", Namespace="http://oreilly.com")]
public class CustomerEntity { ... }

Attribute parameters have two categories: positional or named.

In the code above the first argument is a positional parameter; The second is a named parameter.

Positional parameters correspond to parameters of the attribute type's public constructors.

Named parameters correspond to public fields or public properties on the attribute type.

Related Topics