1

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?

Hooman Limouee
  • 1,143
  • 2
  • 21
  • 43
  • 1
    Maybe it would be easier to define a class with a generic property and the custom properties you want. https://stackoverflow.com/questions/2587236/generic-property-in-c-sharp – Matt Mar 20 '20 at 21:00
  • @Matt _ Maybe the link you mentioned is a part of the answer, but the other part is how to add more attributes to the property? – Hooman Limouee Mar 20 '20 at 21:07
  • 1
    you would just add additional instance properties to the custom Generic property backed class. – Matt Mar 20 '20 at 21:08
  • 1
    I checked the what's new for C# 6 to 8 and could not find anything new. https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8 (and the links to versions 6.0 - 7.3 are also there). Therefore, I think this may be achieved, painfully, using a custom type descriptor: https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.icustomtypedescriptor?view=netframework-4.8 The first two sentences are promising: The ICustomTypeDescriptor interface allows an object to provide type information about itself. Typically, this interface is used when an object needs dynamic type information – Oguz Ozgul Mar 20 '20 at 21:14

1 Answers1

2

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.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
AEdev52
  • 21
  • 2
  • 1
    Note that suggested way prevents `new SomeClass (..)` calls as you'd need to create your instances via reflection using newly created type. – Alexei Levenkov Mar 20 '20 at 21:53