2

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?

4
  • 1
    Maybe it would be easier to define a class with a generic property and the custom properties you want. stackoverflow.com/questions/2587236/generic-property-in-c-sharp Commented Mar 20, 2020 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? Commented Mar 20, 2020 at 21:07
  • 1
    you would just add additional instance properties to the custom Generic property backed class. Commented Mar 20, 2020 at 21:08
  • 1
    I checked the what's new for C# 6 to 8 and could not find anything new. 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: docs.microsoft.com/en-us/dotnet/api/… 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 Commented Mar 20, 2020 at 21:14

1 Answer 1

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.

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

1 Comment

Note that suggested way prevents new SomeClass (..) calls as you'd need to create your instances via reflection using newly created type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.