2

Ok, consider the following scenario:

public class Foo()
{
    [FooProperty]
    public int Blah { get { .... } }

    ...
}

[AttributeUsage(AttributeTargets.Property)]
public class FooPropertyAttribute: Attribute
{
    public FooPropertyAttribute()
    {
        //Is there any way to get at runtime a PropertyInfo of the declaring property 'Foo.Blah'?
    }

    ...
}

I know this is probably not a good idea but recently, while prototyping some classe, the question came up and I'm curious to know if this is even possible.

InBetween
  • 32,319
  • 3
  • 50
  • 90

1 Answers1

1

Since you actively have to hunt for these attributes you can do whatever you want.

For instance, if you have code like this:

foreach (var propertyInfo in type.GetProperties())
{
    if (propertyInfo.IsDefined(typeof(FooPropertyAttribute), true))
    {
        var attr = (FooPropertyAttribute)propertyInfo.GetCustomAttributes(typeof(FooPropertyAttribute), true)[0];
        attr.FooMethod(propertyInfo); // <-- here
    }
}

Then as you can see, you can pass in the property info object to it.

Other than this, no, not with just built-in attribute system of .NET.

There may be support in things like PostSharp to get hold of it but this is a completely different question.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
  • Thanks! It seems there is no way to do what I was asking using Reflection. In the link provided by Eugene Podskal the only solution seems to be a stack-walking approach...not a good idea. – InBetween Aug 18 '14 at 09:07
  • 1
    The stack-walking approach only works when the code actually runs, and attributes does not run unless you specifically go hunt for them and run code in them. In other words, stuffing the stack-walking approach into the attribute constructor would not work unless you also have the kind of code I posted in the answer. And if you have to provide that code anyway, you might as well just do what I did, call a method on the attribute and pass in the member it was found on. So no, there is no way to do what you want to do, and the stack-walking approach won't work alone either. – Lasse V. Karlsen Aug 18 '14 at 09:12