views:

65

answers:

3

I am trying to create a generic method that will read an attribute on a class and return that value at runtime. How do would I do this?

Note: DomainName attribute is of class DomainNameAttribute.

[DomainName(“MyTable”)]
Public class MyClass : DomianBase
{}

What I am trying to generate:

//This should return “MyTable”
String DomainNameValue = GetDomainName<MyClass>();
+1  A: 

Here's a good tutorial if you haven't seen it before http://msdn.microsoft.com/en-us/library/aa288454(VS.71).aspx

In particular of interest to you is the section here, called Accessing the Attribute http://msdn.microsoft.com/en-us/library/aa288454(VS.71).aspx#vcwlkattributestutorialanchor3

Driss Zouak
+4  A: 
public string GetDomainName<T>()
{
    var dnAttribute = typeof(T).GetCustomAttributes(
        typeof(DomainNameAttribute), true
    ).FirstOrDefault() as DomainNameAttribute;
    if (dnAttribute != null)
    {
        return dnAttribute.Name;
    }
    return null;
}

UPDATE:

This method could be further generalized to work with any attribute:

public static class AttributeExtensions
{
    public static TValue GetAttributeValue<TAttribute, TValue>(
        this Type type, 
        Func<TAttribute, TValue> valueSelector) 
        where TAttribute : Attribute
    {
        var att = type.GetCustomAttributes(
            typeof(TAttribute), true
        ).FirstOrDefault() as TAttribute;
        if (att != null)
        {
            return valueSelector(att);
        }
        return default(TValue);
    }
}

and use like this:

string name = typeof(MyClass)
    .GetAttributeValue((DomainNameAttribute dna) => dna.Name);
Darin Dimitrov
Thanks for your diligence in answering the question!
Zaffiro
+2  A: 
System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes(true);

for (int i = 0; i < attributes.Length; i++)
{
    if (attributes[i] is DomainNameAttribute)
    {
        System.Console.WriteLine(((DomainNameAttribute) attributes[i]).Name);
    }   
}
Merritt
@Anyone: Darin's solution is more elegant.
Merritt