Attributes provide the field
attribute target.
This however only seems to help when targeting the backing field of an auto-property.
If I add an attribute to a specific object field, the type of the field is known at compile time. Is there a way to target that attribute at fields on that type?
Example:
// class in my code
public class Foo
{
[field: SomeAttribute] // <-- this should target TargetClass.TargetField, is it possible and how?
public Bar TargetClass;
}
// class that might be defined in a library or part of code that I cannot edit or add attributes to
public class Bar
{
public int TargetField;
}
I've looked through the Attribute documentation, but can't find anything related to this particular usecase. This leads me to think it's not directly supported.
However, intuitively I would think the compiler has all the information necessary to make this kind of targeting possible so maybe this is something that has been suggested but isn't implemented yet?
That's not a thing you can do. The attribute would need to be on the actual type/member intended. There is a concept of runtime properties in the "descriptor" model (rather than the reflection model) which would allow more flexibility, but that only applies in niche scenarios, so honestly: it isn't worth trying to explain.