Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

petapoco

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!

like image 655
ovatsug25 Avatar asked Dec 14 '22 05:12

ovatsug25


2 Answers

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>();
like image 94
Ivan Stoev Avatar answered Dec 27 '22 10:12

Ivan Stoev


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);
        }
    }    
}
like image 30
Ryan Mann Avatar answered Dec 27 '22 10:12

Ryan Mann