How to get the value of a custom attribute in C#

In a recent project, I needed to get the value of a custom attribute that was set on various class properties. More precisely, the custom attribute was a string that needed to be evaluated programmatically to see if it matched a given value. This particular case came up during unit testing of localized strings in a web application, but may be applicable to a wide variety of use cases involving custom attributes.

In this example, there is a class that sets a custom attribute like this:

public class UserAccount
{
    [LocalizedDisplayName("SOME_RESOURCE_ID")]
    public string UserAccountName { get; set; }
    ...
}

This attribute is referenced throughout the application to display the correct text for the current culture, but the problem is that there is no inherent mechanism to get the actual string value of the resource associated with the given class property for testing purposes. The solution was to create a utility method which does just that:

public static object GetAttributeValue(Type objectType, string propertyName, Type attributeType,

string attributePropertyName)
{
    var propertyInfo = objectType.GetProperty(propertyName);
    if (propertyInfo != null)
    {
        if (Attribute.IsDefined(propertyInfo, attributeType))
        {
            var attributeInstance = Attribute.GetCustomAttribute(propertyInfo, attributeType);
            if (attributeInstance != null)
            {
                foreach (PropertyInfo info in attributeType.GetProperties())
                {
                    if (info.CanRead &&
                      String.Compare(info.Name, attributePropertyName,
                      StringComparison.InvariantCultureIgnoreCase) == 0)
                    {
                        return info.GetValue(attributeInstance, null);
                    }
                }
            }
        }
    }
    return null;
}

This method is in an AttributeUtil class. An example call to the method looks like this:

var value = AttributeUtil.GetAttributeValue(typeof(UserAccount), "UserAccountId",
                                             typeof(LocalizedDisplayNameAttribute),"DisplayName");

It was surprisingly hard to find relevant information for this particular problem, so I hope you found this useful. A complete example project is available in our codeplex repository.

GetAttributeValue

As an exercise to the reader, you may choose to package GetAttributeValue as an extension method on the Attribute class itself. Also, beware that this will not work against attributes whose value is an array type, because we’re passing NULL as the second parameter to PropertyInfo.GetValue method.

Advertisements
Tags:

3 Comments to “How to get the value of a custom attribute in C#”

  1. Thank you very much. It is usefull

  2. Thanks! I was looking for this and like you said had a hard time finding information. This worked on the first try for me.

  3. i have searched for hours on how to do this thanks so much for sharing

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: