Introduction
An attribute is a powerful .NET language feature that is attached to a target
programming element (e.g., a class, method, assembly, interface, etc.) to customize
behaviors or extract organizational information of the target at design, compile,
or runtime.
The paradigm of attributed programming first appeared in the Interface
Definition Language (IDL) of COM interfaces. Microsoft extended the concept
to Transaction Server (MTS) and used it heavily in COM+. It is a clean approach
to associate metadata with program elements and later use the metadata at design,
compile or run time to accomplish some common objectives. In .NET, Microsoft
went a step further by allowing the implementation of attributes in the source
code, unlike the implementation in MTS and COM+ where attributes were defined
in a separate repository. To understand the power of attributes, consider the
serialization of an object. In .NET, you just need to mark a class Serializable
to make its member variables as Serializable.
For example:
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Soap;
[Serializable]
public class User{
public string userID;
public string password;
public string email;
public string city;
public void Save(string fileName){
FileStream s=new FileStream(fileName,FileMode.Create);
SoapFormatter sf=new SoapFormatter();
sf.Serialize(s,this);
}
static void Main(string[] args){
User u=new User();
u.userID="firstName";
u.password="Zxfd12Qs";
u.email="asdf@qwer.com";
u.city="TheCity";
u.Save("user.txt");
}
}
Note: You may have to Add a reference to assembly System.Runtime.Serialization.Formatters.Soap.dll
The above example illustrates the power of attributes. We do not have to tell
what to serialize; we just need to mark the class as serializable by annotating
the class with Serializable attribute. Of course, we need to tell the serialization
format (as in the Save method).