views:

149

answers:

2

Hi.

[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.

+2  A: 

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
Hmm, may be i'm looking on the problem from opposite end than i should.
Feryt
Yes, you start by a type, then get the properties and finally read the custom attributes applied to a given property.
Darin Dimitrov
+1. But the phrase "Usually you would use" needs to be: "You have to use".
Hans Passant
A: 

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.

Courtney de Lautour