Question

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; } }
}
Was it helpful?

Solution

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

OTHER TIPS

Using CallerMemberNameAttribute from .NET 4.5:

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top