Scott Dorman

ephemeral segment

  Home  |   Contact  |   Syndication    |   Login
  603 Posts | 10 Stories | 862 Comments | 51 Trackbacks

News


Post Categories

Image Galleries


Microsoft Store


Creative Commons License



Locations of visitors to this page

Subscribers to this feed

TwitterCounter for @sdorman

View blog authority

Add to Technorati Favorites

Windows Live Alerts

AddThis Social Bookmark Button

LinkedIn profile

Community Credit profile

The Code Project

Follow me on Twitter

Get Free Shots from Snap.com

Community Credit Hall of Fame

Get Feedghost

Xobni outlook add-in for your inbox



Support This Site

Tag Cloud


Article Categories

Archives

Post Categories

Image Galleries

Attribute programming has a lot of benefits and, when done correctly, can greatly simplify the amount of code that you need to write. One drawback to using attributes is that the code required to retrieve a custom attribute from a type is a bit cumbersome and is very repetitious.

Given a type, the simplest way to retrieve a custom attribute is code like

CustomAttribute attribute = Attribute.GetCustomAttribute(customType.GetType(), typeof(CustomAttribute), true) as CustomAttribute;

While this is simple code, it doesn’t handle any error conditions and requires that you always remember to perform the cast. A more complete method would look like

public static CustomAttribute GetAttribute(MemberInfo element)
{
CustomAttribute attribute = null;

try
{
attribute = Attribute.GetCustomAttribute(element, typeof(CustomAttribute), true) as CustomAttribute;
}
catch
{
// We aren't really interested in the exceptions here, but if we do get an exception
// just return null;
attribute = null;
}

return attribute;
}

This nicely encapsulates the error handling and casting, but introduces another drawback. In order to make use of this method you would need to include it on every custom attribute you create, being sure to change the types appropriately.
 
We can make this more practical by changing to a generic extension method with very little effort
public static T GetAttribute<T>(this MemberInfo element) where T: Attribute
{
T attribute = null;

if (element != null)
{
try
{
attribute = Attribute.GetCustomAttribute(element, typeof(T), true) as T;
}
catch
{
// We aren't really interested in the exceptions here, but if we do get an exception
// just return null;
attribute = null;
}
}

return attribute;
}

The benefit here is that, because this is implemented as an extension method it is available as if it were a real method call on any class derived from MemberInfo, which happens to be the base class for all of the Type classes.
 
Now, we can define our custom attributes without any special consideration to providing a strongly typed GetAttribute method and when we want to retrieve a custom attribute, we can use code that now looks like
CustomAttribute attribute = customType.GetType().GetAttribute<CustomAttribute>();

It might not look like a major change in the calling site, but we are now able to quickly and easily get a strongly typed attribute given an instance type.

Technorati Tags: ,
Digg This
posted on Monday, June 08, 2009 1:31 PM

Feedback

# re: Getting a custom attribute 6/10/2009 1:03 PM Anthony Trudeau
I've used an extension method for this purpose for some time. I have a couple of tips that hopefully will help you.

First, you don't need to check if element is null. It's an extension method therefore it's called off an instance. It doesn't matter what the instance value is.

Second, don't catch all exceptions like you're doing. It can have bad side effects. The GetCustomAttribute method can throw several exceptions. The ArgumentNullException and ArgumentException are not applicable here. The strong-typing of the extension method eliminates them. The others are NotSupportedException, AmbiquousMatchException, and TypeLoadException. I won't rehash the documentation on them, but these are all best handled by user code if and when necessary.

# re: Getting a custom attribute 6/17/2009 3:56 PM Rufus
You might want to look at the codeproject articles at DocumentLab as they address this specific issuse.

# re: Getting a custom attribute 8/4/2009 3:01 PM Scott
Anthony, The reason for checking if element is null is to prevent an ArgumentNullException from being thrown by Attribute.GetCustomAttribute and is generally a good idea anyway when you are extending a reference object since it is entirely possible that the instance is null. It is legal to invoke an extension method on a null object although the actual method invoked may then subsequently fail.

Yes, catching exceptions in a general sense like I am doing is bad and can have side effects. The strong typing would eliminate the possibility of the ArgumentNullException or ArgumentException as it relates to the attributeType parameter, but not necessarily the ArgumentNullException for element. All of that aside, for the context in how I was using the extension method, I really wasn't interested in knowing or doing anything about any of the possible exceptions.

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: