C# Attributes

In this chapter you will learn:

  1. What is an Attribute
  2. How to use an attribute
  3. Example for Attribute Targets
  4. Specifying Multiple 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  .  j  ava  2s . c  o m
[Serializable] [Obsolete] [CLSCompliant(false)]
public class Bar {...}

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

Next chapter...

What you will learn in the next chapter:

  1. How to use obsolete attribute
  2. Example for obsolete attribute
  3. Obsolete attribute with error message and compiler error
  4. Generate a compilation error rather than a warning
Home »
  C# Tutorial »
    C# Types »
      C# Attribute
C# Attributes
C# Obsolete Attribute
C# Conditional Attribute
C# Custom Attributes
C# Attribute parameter
C# Attribute Usage
C# Attribute reflection