1

I have a property that looks like this:

<DataElement(0, 4)>
Private Property RiffId As String
   Get
      Dim mb As MethodBase = MethodBase.GetCurrentMethod()
      Dim de As DataElementAttribute = mb.GetCustomAttribute(Of DataElementAttribute)()
      ...
  End Get
  Set(value As String)
     ...
  End Set
End Property

(This project is VB but C# answers are perfectly welcome.)

The variable de contains null/Nothing because the attribute applies to the property as a whole, not to the getter, which is what the mb variable contains. Is there a convenient and direct way to get to the "parent" method base without getting the name of the getter, stripping off the leading "get_", and searching the properties of the class to get the attributes of the property? I don't see one but perhaps I'm overlooking it.

Chris Dunaway
  • 10,974
  • 4
  • 36
  • 48
trw
  • 239
  • 1
  • 11
  • Can you explain why you would need this to work like this? Because it looks like a hack for some other problem. – Silvermind Jan 10 '19 at 16:14
  • I want to access the attribute of the property. Is that so unusual? – trw Jan 10 '19 at 16:17
  • 4
    `Is that so unusual?` <= Actually it is. Generally attributes are used to decorate code and can then be read/consumed/used by code outside the decoration point. If the code that is decorated is trying to access the attribute that decorates it it usually indicates a defect in the design. The whole point is to add/extend functionality by decoration and the code being decorated should be none the wiser. – Igor Jan 10 '19 at 16:20
  • This question (https://stackoverflow.com/questions/3628630/use-reflection-to-get-attribute-of-a-property-via-method-called-from-the-setter) discusses it. I was curious. – trw Jan 10 '19 at 16:24

1 Answers1

2

Well there is no absolut direct way, but you can search rather safe for it (no strings involved). Have a look at this example:

using System;
using System.Linq;
using System.Reflection;

public class Program
{
    [ObsoleteAttribute("foo")]
    public static string MyProp
    {
        get
        {
            var mb = MethodBase.GetCurrentMethod();
            var prop = mb.DeclaringType.GetProperties().Single(x => x.GetGetMethod() == mb);
            return prop.GetCustomAttribute<ObsoleteAttribute>().Message;
        }
    }

    public static void Main()
    {
        Console.WriteLine(MyProp);
    }
}

The result is:

foo

thehennyy
  • 4,020
  • 1
  • 22
  • 31