Search code examples
c#petapoco

Is there a way for me to access a C# class attribute?


Is there a way for me to access a C# class attribute?

For instance, if I have the following class:

...
[TableName("my_table_name")]
public class MyClass
{
    ...
}

Can I do something like:

MyClass.Attribute.TableName => my_table_name

Thanks!


Solution

  • You can use Attribute.GetCustomAttribute method for that:

    var tableNameAttribute = (TableNameAttribute)Attribute.GetCustomAttribute(
        typeof(MyClass), typeof(TableNameAttribute), true);
    

    However this is too verbose for my taste, and you can really make your life much easier by the following little extension method:

    public static class AttributeUtils
    {
        public static TAttribute GetAttribute<TAttribute>(this Type type, bool inherit = true) where TAttribute : Attribute
        {
            return (TAttribute)Attribute.GetCustomAttribute(type, typeof(TAttribute), inherit);
        }
    }
    

    so you can use simply

    var tableNameAttribute = typeof(MyClass).GetAttribute<TableNameAttribute>();