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:

```csharp
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:

```csharp
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 &amp;&amp;
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:

```csharp
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](https://github.com/yojimbocorp/blog-posts/tree/master/GetAttributValue)

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.