Getting started with attributes – part V

After all, I’ve decided to write another post about custom attributes. In the last post, I’ve mentioned the use of the CustomAttributeData type. Since I’ve received a couple of questions about its use, I thought it would be a good idea to show an example of how one can use this class to check for specific values. So, I’ll just start by introducing the custom attribute and some code that applies it to a property:

classMyAttribute:Attribute {

    public MyAttribute( string someValue ) {

        SomeValue = someValue;

    }

    publicString SomeValue { get; privateset; }

    publicString SomeOtherValue { get; set; }

}

classStudent {

    [My(“Howdy”, SomeOtherValue = “there!”)]

    publicString Nome { get; set; }

    publicString Morada { get; set; }

}

In the previous post, we’ve already saw how to check if an attribute is applied to a specific target. So, we won’t be performing that check again and I’ll just show you how to recover the values applied to the properties of the attribute:

var prop = typeof( Student ).GetProperty( “Nome” );

var attrib = CustomAttributeData.GetCustomAttributes( prop ).First();

//positional arguments can be obtained from the ConstructorArguments prop

var positionalArgs = attrib.ConstructorArguments;

for(var i = 0; i < positionalArgs.Count; i++){

    Console.WriteLine( “arg at pos {0} has value {1},

        i, positionalArgs[i].Value);

}

//named arguments can be recovered through NamedArguments

var namedArgs = attrib.NamedArguments;

foreach( CustomAttributeNamedArgument t in namedArgs ) {

    Console.WriteLine( “arg {0} has value {1},

                       t.MemberInfo.Name, t.TypedValue.Value);

}

I believe the code is rather simple: positional parameters are represented by CustomAttributeTypedArgument instances, which allow us to recover its value and type. On the other hand, named parameters are represented by CustomAttributeNamedArgument instances, where each item exposes a Name (that identifies the custom attribute’s property that is being initialized) and a CustomAttributeTypedArgument property (TypedValue) which allows us to recover its value and type.

And I guess this wraps it up for now! Stay tuned for more.

Advertisements

~ by Luis Abreu on July 21, 2011.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: