.ttributes have mostly decorative impact on your applications and are used mostly by Reflection. Attributes can be applied almost everywhere in your code warring from get accessor to entire assembly.

How to create your custom Attributes?

You create it like a class, but it is important that a class inherits from a Attribute class or a class that inherits from a Attribute class. You should also apply System.AttributeUsage over your class, where is decided how this attributes class can be used. Attributes are assigned to a class, method… by writing square brackets inside which is written attributes name, also if your attribute is named MyCustomAttribute, you need not to write attribute in your Attributes name because compiler will know what to do.

So let’s create our attribute:

This Attribute can be applied almost everywhere in your code. List of possible usages is here:

  • Assembly
  • Module
  • Class
  • Struct
  • Enum
  • Constructor
  • Method
  • Property
  • Field
  • Type
  • Event
  • Interface
  • Parameter
  • Delegate
  • ReturnValue
  • GenericParameter

 

We can set constraints to our constructor, so for example that it can be only applied to Methods and Properties:

Note that we used | character to separate two possible usages.

 

There is also feature to use same Attribute multiple times on a same target, that feature can be turned on or off using Allow multiple option (default value is false).

 

If we want to enable or disable that the attribute is inherited by classes that are derived from a class that is attributed we can use Inherited option (default is true).

 

How to apply Attributes?

Simply, put above method,class,property…  Attributes name inside square brackets

 

Common Uses for Attributes

The following list is copied from MSDN Library:

  • Marking methods using the WebMethod attribute in Web services to indicate that the method should be callable over the SOAP protocol. For more information, see WebMethodAttribute.
  • Describing how to marshal method parameters when interoperating with native code. For more information, see MarshalAsAttribute.
  • Describing the COM properties for classes, methods, and interfaces.
  • Calling unmanaged code using the DllImportAttribute class.
  • Describing your assembly in terms of title, version, description, or trademark.
  • Describing which members of a class to serialize for persistence.
  • Describing how to map between class members and XML nodes for XML serialization.
  • Describing the security requirements for methods.
  • Specifying characteristics used to enforce security.
  • Controlling optimizations by the just-in-time (JIT) compiler so the code remains easy to debug.
  • Obtaining information about the caller to a method.

 

How to consume Attributes is explained in articles concerning Reflection.