Click here to Skip to main content
6,594,432 members and growing! (16,287 online)
Email Password   helpLost your password?
License: The Code Project Open License (CPOL)

Getting a custom attribute

By Scott Dorman

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
Windows
Version:2 (See All)
Posted:8 Jun 2009
Views:2,479
Bookmarked:4 times
Technical Blog
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
1 vote for this technical blog.
Popularity: 0.00 Rating: 4.00 out of 5

1

2

3
1 vote, 100.0%
4

5
A Technical Blog article. View entire blog here.

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Scott Dorman


Member
Scott is a C# MVP and has been involved with computers in one way or another for as long as he can remember, but started professionally in 1993. After spending 6 years as a systems administrator, Scott branched out and started developing eCommerce store fronts. From there, he has worked on many different projects and has been working with .NET and C# since 2001.

He has worked at Fortune 500 companies and privately held start-ups focused on IT consulting where he gained experience in embedded systems design and software development to systems administration and database programming, and everything in between.

Although his primary focus right now is commercial software applications using Microsoft .NET technologies, he prefers building infrastructure components, reusable shared libraries and helping companies define, develop and automate process standards and guidelines.

Scott is currently working as a senior developer and architect on the Gulf coast of Florida, where he lives with his three cats.
Occupation: Software Developer (Senior)
Location: United States United States

Other popular Custom Controls articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 3 of 3 (Total in Forum: 3) (Refresh)FirstPrevNext
GeneralA variation on this theme that handles multiple attributes and caches results ... PinmemberHightechRider13:07 8 Jun '09  
GeneralRe: A variation on this theme that handles multiple attributes and caches results ... PinmemberScott Dorman4:23 9 Jun '09  
GeneralRe: A variation on this theme that handles multiple attributes and caches results ... PinmemberHightechRider9:01 9 Jun '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 8 Jun 2009
Editor: Sean Ewington
Copyright 2009 by Scott Dorman
Everything else Copyright © CodeProject, 1999-2009
Web21 | Advertise on the Code Project