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!
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>();
                        You can use reflection to get it. Here's is a complete encompassing example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
    public class TableNameAttribute : Attribute
    {
        public TableNameAttribute(string tableName)
        {
            this.TableName = tableName;
        }
        public string TableName { get; set; }
    }
    [TableName("my_table_name")]
    public class SomePoco
    {
        public string FirstName { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var classInstance = new SomePoco() { FirstName = "Bob" };
            var tableNameAttribute = classInstance.GetType().GetCustomAttributes(true).Where(a => a.GetType() == typeof(TableNameAttribute)).Select(a =>
            {
                return a as TableNameAttribute;
            }).FirstOrDefault();
            Console.WriteLine(tableNameAttribute != null ? tableNameAttribute.TableName : "null");
            Console.ReadKey(true);
        }
    }    
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With