Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real world use of custom .NET attributes

What kind of things have you used custom .NET attributes for in the real world?

I've read several articles about them, but I have never used custom attributes.

I feel like I might be overlooking them when they could be useful.

I am talking about attributes that you create, not ones that are already included in the framework.

like image 916
TWA Avatar asked Jun 21 '09 04:06

TWA


2 Answers

I created a scripting engine, and tagged various methods with the [Command] attribute. This meant that these functions were exposed to the scripting engine.

Example:

[Command(HelpText = "Lists active users")]
void ListUsers(void)
{

}

[Command(HelpText = "Terminate a specific user's connection")]
void EndConnection(int userID)
{

}

And as used:

MyScriptEngine>>  Help
Available Commands are:
    ListUsers: Lists active users
    EndConnection {userID}: Terminate a specific user's connection

MyScriptEngine>> EndConnection 3
    User 3 (Michael) has had his connection terminated.

MyScriptEngine>>
like image 78
abelenky Avatar answered Oct 12 '22 05:10

abelenky


I've used them "custom" attributes for validation (ie. marking a field to be validated with my own "credit card validation") and custom LinqToLucene analyzers I've written (ie. specifying which analyzer to use on a given field).

The validation code, for example, would look something like this:

public class Customer
{
     [CreditCardValidator]
     string creditCardNumber;

     [AddressValidator]
     string addressLineOne
}

When the object above is validated, each field is validated with the appropriate validator thanks to the "custom" attribute.

In the LinqToLucene stuff I've written custom attributes are nice because they allow you to find (through reflection) specific fields at run time. For example, if you have a customer object, you may be interested in getting all the properties that have been marked as "index me": a custom attribute lets you do this easily since it exposes meta-data about the object in a manner that is easy to query.

like image 41
Esteban Araya Avatar answered Oct 12 '22 06:10

Esteban Araya