C# Attributes
In this chapter you will learn:
- What is an Attribute
- How to use an attribute
- Example for Attribute Targets
- 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:
- How to use obsolete attribute
- Example for obsolete attribute
- Obsolete attribute with error message and compiler error
- Generate a compilation error rather than a warning