Monday, February 07, 2005

.NET Attributes

Stumbled upon a nice little command-line parser at CodeProject. The tool allows you to write code like the following in your console apps.

[CommandLineSwitch("help","Show the help")]

public bool ShowHelp
{
get { return m_ShowHelp; }
set { m_ShowHelp = value; }
}

The tool would return the value of the ShowHelp property depending upon the value of the "help" command-line option.

The basic idea here is to be able to declaratively specify the command-line options and their types, supported by a program, and delegate all that is required to parse the command-line, determining its value and performing validation checks to a separate piece of reusable code shipped with the tool.

Don't you think access modifiers like public and private greatly simplify what you're trying to express about class members by letting the compiler enforce it! .NET lets you attach descriptive declarations to annotate types, fields, methods and properties in the form of attributes. Attributes allow you to have your own descriptive elements and thus can extremely simplify an API if used properly. Information about attributes can be extracted using Reflection. (More info)

I used attributes in EtherYatri.NET to ease the communication between different mobile-agents. A mobile-agent can simply mark a method with the AgentWebMethod attribute to allow it to be invoked by other mobile-agents. The toolkit does the hard-work of determining if the method being requested was indeed exposed by the specified agent, invoking the requested method on the specified agent, passing the supplied arguments and returning the results of method invocation. Go here for details.