Tom Atwood
Tom Atwood

Reputation: 478

Get property value to use within custom attribute

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?

Upvotes: 3

Views: 707

Answers (1)

Tom Atwood
Tom Atwood

Reputation: 478

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.

Upvotes: 3

Related Questions