Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 598
kabucey Avatar asked Feb 24 '10 21:02

kabucey


People also ask

How do I find custom attributes?

Right-click on a user, then click Properties. Click the Attribute Editor tab, then confirm that the custom attribute you created is listed in the "Attribute" column (e.g., LastPassK1).

How do you access the system attribute of a system object?

Select Adminstration > Site Development > System Object Types. Select the Product object link and then the Attribute Definitions tab. Notice the list of attribute definitions already created for this system object.

Which method is used to retrieve the values of the attributes?

First, declare an instance of the attribute you want to retrieve. Then, use the Attribute. GetCustomAttribute method to initialize the new attribute to the value of the attribute you want to retrieve. Once the new attribute is initialized, you simply use its properties to get the values.


1 Answers

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; }      } } 
like image 96
Nick Randell Avatar answered Sep 20 '22 01:09

Nick Randell