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?

4
  • See stackoverflow.com/questions/916904/… Commented Feb 25, 2015 at 7: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 stackoverflow.com/questions/6637679/… Commented Feb 25, 2015 at 8: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. Commented Feb 25, 2015 at 23:04
  • What do you want to achieve, and why do you think that attributes is the right way to do that? Commented Feb 25, 2015 at 23:52

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.