5
[MyAttribute()]
public string Name { get; set; }

In MyAttribute I need to know the name of associated property, is it possible?

EDIT:

I need to use it in text formatting.

Re Captcha
  • 3,125
  • 2
  • 22
  • 34
Feryt
  • 2,262
  • 2
  • 22
  • 32

2 Answers2

8

No, this is not possible. Usually you would use reflection to read attributes applied on a given property, so you already know the property. Example:

var properties = typeof(SomeType).GetProperties();
foreach (var property in properties)
{
    var attributes = property.GetCustomAttributes(typeof(MyAttribute), true);
    if (attributes.Count > 0)
    {
        // look at property.Name here
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

You can use a PostSharp aspect to do the job. I had a similar question a while back, which was almost the same thing. You can see comments on the answer for more info about some of the implications that you might encounter.

Community
  • 1
  • 1