3

I have been looking for an example of how to get a property's value from within a custom attribute's code.

Example for illustration purposes only: We have a simple book class with only a name property. The name property has a custom attribute:

public class Book
{
    [CustomAttribute1]
    property Name { get; set; }
}

Within the custom attribute's code, I would like to get the value of the property on which the attribute has been decorated:

public class CustomAttribute1: Attribute
{
    public CustomAttribute1()
    {
        //I would like to be able to get the book's name value here to print to the console:
        // Thoughts?
        Console.WriteLine(this.Value)
    }
}

Of course, "this.Value" does not work. Any thoughts?

leppie
  • 115,091
  • 17
  • 196
  • 297
Tom Atwood
  • 468
  • 3
  • 17
  • See http://stackoverflow.com/questions/916904/how-to-i-get-the-property-belonging-to-a-custom-attribute – haim770 Feb 25 '15 at 07:58
  • Well it depends of your use case, sometimes its easier just to use CustomAttribute[name="something"]. But I think you should use reflection if you want, what you want. have a look at http://stackoverflow.com/questions/6637679/reflection-get-attribute-name-and-value-on-property – madz Feb 25 '15 at 08:00
  • Actually, that is the opposite of what I am looking for (the above link allows for finding properties where an attribute has been provided, and you get the name and value). What I am looking for is once the CustomAttribute code is called, the CustomAttribute code knows that it was called from the name property and can detect the property's value. If I could detect the class name and property name from within CustomAttribute, I could use Reflection to get the value, but I can't seem to do that. – Tom Atwood Feb 25 '15 at 23:04
  • What do you want to achieve, and why do you think that attributes is the right way to do that? – user4003407 Feb 25 '15 at 23:52

1 Answers1

3

OK, I figured it out. This is only available with .Net 4.5 and later though.

In the System.Runtime.CompilerServices library, there is a CallerMemberNameAttribute class available. To get the name of the calling class, there is a CallerFilePathAttribute class that returns the full path of the calling class for later use with Reflection. Both are used as follows:

public class CustomAttribute1: Attribute
{
    public CustomAttribute1([CallerMemberName] string propertyName = null, [CallerFilePath] string filePath = null)
    {
        //Returns "Name"            
        Console.WriteLine(propertyName);

        //Returns full path of the calling class
        Console.WriteLine(filePath);
    }
}

I hope you find this as helpful in your work.

Tom Atwood
  • 468
  • 3
  • 17