Sadegh
Sadegh

Reputation: 4341

How to get name of property which our attribute is set?

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; } }
}

Upvotes: 47

Views: 38119

Answers (3)

tukaef
tukaef

Reputation: 9214

Using CallerMemberNameAttribute from .NET 4.5:

public CustomAttribute([CallerMemberName] string propertyName = null)
{
    // ...
}

Upvotes: 185

Robert Levy
Robert Levy

Reputation: 29083

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

Upvotes: 0

Matthew Abbott
Matthew Abbott

Reputation: 61609

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; }
}

Upvotes: 3

Related Questions