Note that there are some explanatory texts on larger screens.

plurals
  1. POAccessing attributes on fields using extension method
    primarykey
    data
    text
    <p>I want to check custom attributes on my class members (fields only) by using an extension method.</p> <pre><code>public class DatabaseIdAttribute : Attribute { public int ID { get; set; } public DatabaseIdAttribute(int id) { this.ID = id; } } public class MyClass { [DatabaseId(1)] double Height {get;set;} [DatabaseId(2)] double Width {get;set;} double Area { get { return this.Height * this.Width; } } </code></pre> <p>I want to use LINQ expression in the extension method to access the class field instead of passing magic strings.</p> <pre><code>var myClass = new MyClass(); var attribute = myClass.GetAttribute&lt;DatabaseIdAttribute&gt;(c =&gt; c.Height); </code></pre> <p>Is it possible to achieve?</p> <p>[EDIT]</p> <p>For the time being, I have achieved the following with the help of @leppie </p> <pre><code> public static MemberInfo GetMember&lt;T, R&gt;(this T instance, Expression&lt;Func&lt;T, R&gt;&gt; selector) { var member = selector.Body as MemberExpression; if (member != null) { return member.Member; } return null; } public static T GetAttribute&lt;T&gt;(this MemberInfo member) where T : Attribute { return member.GetCustomAttributes(false).OfType&lt;T&gt;().SingleOrDefault(); } </code></pre> <p>which enables to get the attribute in the following way</p> <pre><code>var c = new MyClass(); var attribute = c.GetMember(m =&gt; m.Height).GetAttribute&lt;DatabaseIdAttribute&gt;(); </code></pre> <p>but I want to be able to access it in the following way</p> <pre><code>var c = new MyClass(); var attribute = c.GetAttribute&lt;DatabaseIdAttribute&gt;(m =&gt; m.Height); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload