41

I'm going to do this without passing any parameter to attribute! Is it possible?

class MyAtt : Attribute {
    string NameOfSettedProperty() {
        //How do this? (Would be MyProp for example)
    }
}

class MyCls {
    [MyAtt]
    int MyProp { get { return 10; } }
}
mcdrummerman
  • 2,360
  • 1
  • 15
  • 9
Sadegh
  • 4,181
  • 9
  • 45
  • 78

3 Answers3

180

Using CallerMemberNameAttribute from .NET 4.5:

public CustomAttribute([CallerMemberName] string propertyName = null)
{
    // ...
}
tukaef
  • 9,074
  • 4
  • 29
  • 45
  • 1
    Awesome. Saves a parameter for an attribute that I'll have to use to decorate properties across the entire project. – Ellesedil Jan 30 '14 at 23:08
  • 2
    Was looking for this but doesn't work [with enums](http://stackoverflow.com/q/28094024/465942) unfortunately.. – Kapé Mar 28 '15 at 00:34
4

Attributes are metadata applied to members of a type, the type itself, method parameters, or the assembly. For you to have access to the metadata, you must have had the original member itself to user GetCustomAttributes etc, i.e. your instance of Type, PropertyInfo, FieldInfo etc.

In your case, I would actually pass the name of the property to the attribute itself:

public CustomAttribute : Attribute
{
  public CustomAttribute(string propertyName)
  {
    this.PropertyName = propertyName;
  }

  public string PropertyName { get; private set; }
}

public class MyClass
{
  [Custom("MyProperty")]
  public int MyProperty { get; set; }
}
Matthew Abbott
  • 60,571
  • 9
  • 104
  • 129
  • 8
    Thanks i know this can be resolved by passing property-name, I'm going to do this without passing property-name. So based on your response it isn't possible. – Sadegh Jan 05 '11 at 17:32
  • Not possible, attributes are not passed information about the members they are attached to. What would be handy is if the `Attribute` instance was passed the `ICustomAttributeProvider` that was used to create it, but sadly this is not the case. – Matthew Abbott Jan 05 '11 at 17:34
  • 3
    This comment is out of date. See below if using .NET 4.5 – Jon Barker Sep 01 '16 at 12:41
0

you can't do it within the attribute class itself. however, you can have a method that takes an object gets a list of that object's properties (if any) that use the attribute. use this API to implement that: http://msdn.microsoft.com/en-us/library/ms130869.aspx

Robert Levy
  • 28,747
  • 6
  • 62
  • 94