I want to dynamically add attributes to properties of a given class, because the project will get bigger and the procedure is totally repeatinglly, something like so :
public class MyAttr : Attribute {
public MyAttr () {
foreach(var prop in properties) {
prop.Attributes.Add([Display(Name = nameof(prop.Name), ResourceType = typeof(Labels))]);
}
}
}
And use it on classes :
[MyAttr]
public class SomeClass {
public string Name {get; set;}
public string Description {get; set;}
}
of course the code above is not a real program, but I tried to make it simple.
Is it possible to do this? or if not, is there a workaround?
Update: I know there's an attribute called CallerMemberName
that retrieves name of a given property, but how to get the property itself and add more attributes to it?
I think you might be able to make something work combining the below answers from other posts.
Access object properties from Attribute: Can C# Attributes access the Target Class?
Add attributes at runtime: How to add an attribute to a property at runtime by creating new types at run-time.
Unless you're going to be making regular changes across all the properties it may just be better to deal with the repetitive work up front. There are inevitably risks/issues down the road when doing stuff across the board like this.