C# Attributes

Description

Attributes are an extensible mechanism for adding custom information to code elements.

You can add declarative information to a program by using an attribute. An attribute defines additional information that is associated with a class, structure, method, and so on.

Syntax

An attribute is defined by a class that inherits (directly or indirectly) from the abstract class System.Attribute.

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

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


[ObsoleteAttribute]
public class Foo {...}

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


[Obsolete]
public class Foo {...}

ObsoleteAttribute is a type declared in the System namespace:

public sealed class ObsoleteAttribute : Attribute {...}

Example

Implicitly, the target of an attribute is the code element it immediately precedes, which is typically a type or type member. However, you can also attach attributes to an assembly. This requires that you explicitly specify the attribute's target.

Here is an example of using the CLSCompliant attribute to specify CLS compliance for an entire assembly:

[assembly:CLSCompliant(true)]

Specifying Multiple Attributes

Multiple attributes can be specified for a single code element.


[Serializable, Obsolete, CLSCompliant(false)]
public class Bar {...}
//  w  w  w .ja  v  a  2s  . c o  m
[Serializable] [Obsolete] [CLSCompliant(false)]
public class Bar {...}

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




















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor