Search code examples
c#.netreflectioncustom-attributes

How to get a custom attribute from object instance in C#


Let's say I have a class called Test with one property called Title with a custom attribute:

public class Test
{
    [DatabaseField("title")]
    public string Title { get; set; }
}

And an extension method called DbField. I am wondering if getting a custom attribute from an object instance is even possible in c#.

Test t = new Test();
string fieldName = t.Title.DbField();
//fieldName will equal "title", the same name passed into the attribute above

Can this be done?


Solution

  • Here is an approach. The extension method works, but it's not quite as easy. I create an expression and then retrieve the custom attribute.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Linq.Expressions;
    
    namespace ConsoleApplication1
    {
        public class DatabaseFieldAttribute : Attribute
        {
            public string Name { get; set; }
    
            public DatabaseFieldAttribute(string name)
            {
                this.Name = name;
            }
        }
    
        public static class MyClassExtensions
        {
            public static string DbField<T>(this T obj, Expression<Func<T, string>> value)
            {
                var memberExpression = value.Body as MemberExpression;
                var attr = memberExpression.Member.GetCustomAttributes(typeof(DatabaseFieldAttribute), true);
                return ((DatabaseFieldAttribute)attr[0]).Name;
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                var p = new Program();
                Console.WriteLine("DbField = '{0}'", p.DbField(v => v.Title));
    
            }
            [DatabaseField("title")]
            public string Title { get; set; }
    
        }
    }