Search code examples
c#attributesmetaprogramming

Can C# attributes access the e.g. PropertyInfo of the Property they are defined on?


I want to encode in attributes some computational definitions of the form "this field is a cached result of some computation on other fields of this class." The solution I have on hand is very incomplete because I can't... well...

Consider the following sketch:

// appropriate `using` declarations omitted for brevity
[AttributeUsage(Property)]
public class FooAttr : Attribute {
    private PropertyInfo _thing;
    public FooAttr() {
        _thing = GetMyProperty();
        System.Console.Out.WriteLn(_thing.Name); // or something else, w/e
    }
    private PropertyInfo GetMyProperty() {
        // magic
    }
}

public class Bar {
    [FooAttr]
    public int Baz { get; set; }
}
// => writes "Baz" to stdout on loading this class

Is it possible to replace // magic with actual code, or is the solution to brute-force iterate over all possible classes and their properties until I find the specific one that matches this FooAttr?

I have scoured google for a straight answer to this question and found none.


Solution

  • Attribute objects are created upon request, and though it would be extremely convenient if there was a way for the attribute constructor to take as an argument the reflection object that produced it by way of GetCustomAttributes or the like, it is not currently possible.

    Instead custom attributes needing this kind of functionality should use a factory pattern, where passing in the reflection object to some method performs the necessary computation, perhaps memoized in static fields in some fashion.