Attributed Programming in .NET Using C#

Attribute Targets and Specifications

All .NET programming elements (assemblies, classes, interfaces, delegates, events, methods, members, enum, struct, and so forth) can be targets of attributes. When they are specified at global scope for an assembly or module, they should be placed immediately after all using statements and before any code. Attributes are placed in square brackets by immediately placing them before their targets, as in

[WebMethod]
public string CapitalCity(string country){
     //code to return capital city of a country
}

In the absence of any target-specifier, the target of the above attribute defaults to the method it is applied to (CapitalCity). However, for global scoped attributes, the target-specifier must be explicitly specifed, as in

[assembly:CLSCompliant(true)]

Multiple attributes can be applied to a target by stacking one on top of another, or by placing them inside a square bracket and then separating adjacent attributes by commas.

Attributes are classes (we will discuss that later) and as such are able to accept parameters in their specifications (like class constructor). There are two types of parameters, positional and named, that attributes accept in their usage. Positional parameters are like constructor arguments and their signature should match one of the constructors of the attribute class. For example,

[assembly:CLSCompliant(true)]

In the above example, CLSCompliant attribute accepts a boolean parameter in one of its constructors and it should be used with a boolean parameter. Positional parameters are always set through constructors of the attribute.

Named parameters are defined as non-static property in the attribute class declaration. They are optional and, when used, their names should exactly match the name of the property defined in the attribute class declaration. For example,

[WebMethod(EnableSession=true)]

In the above attribute usage, EnableSession is a named parameter and it is optional. It also tells us that WebMethod attribute has a property called EnableSession.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” - Martin Fowler