Adding custom attributes to properties at run time in C# RRS feed

  • Question

  • hi all,
    Is it possible to add attributes to properties dynamically? I'm quite a beginner in dealing with Attributes and would appreciate any kind of help.
    Let me explain my scenario: I have a propertyGrid which has two tabs, one is to display inputProperties and other tab is to display result properties. I want to control my properties dynamically in both input and output tabs. For input tab, I suppose I can get them done by setting the BrowsableAttribute. But to display the output/result properties,  I have the following custom ResultPropertyAttribute. When I apply [ResultProperty] attribute to my properties, those properties gets displayed in the output tab. But I want to dynamically set this attribute to my property based on certain conditions, so that only if my condition gets satisfied i want my output properties to be displayed


    public class ResultPropertyAttribute:Attribute


    private string resultName;

    public string ResultName


    get{return resultName;}

    set{resultName = value;}



    In my continuos research, I found that its not possible to add attributes to properties dynamically

    but in few different forums, I read we can make use of TypeDescriptor.AddAttributes() and I tried to implement them but the attribute doesn't seem to have been added to my property. I tried the below

    //Gets existing attributes associated with "MyPropertyName"

    AttributeCollection attributes = TypeDescriptor.GetProperties(this)["MyPropertyName"].Attributes;

    //trying to add ResultPropertyAttribute to my property

    TypeDescriptor.AddAttributes("MyPropertyName", new ResultPropertyAttribute());

    //querying again to check if the ResultPropertyAttribute has been added but => I don't see them being added

    attributes = TypeDescriptor.GetProperties(this)["MyPropertyName"].Attributes;

    Can someone please guide me what is wrong in here ? I would also appreciate if there is any other better solution in what I am trying to achieve.

    Thank you in advance for your help.

    • Edited by jessica2030 Sunday, February 21, 2016 10:42 AM
    Sunday, February 21, 2016 10:38 AM


  • The TypeDescriptor.AddAttributes method adds an attribute to an instance:

    TypeDescriptor.AddAttributes(this, new ResultPropertyAttribute());

    If you want to add an attribute to a property of an instance, you could refer to the following thread and the two helper classes:

    I am afraid that there is no built-in method that directly lets you add an attribute to a single property of an instance.

    Hope that helps.

    Please remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question. Please don't ask several questions in the same thread.

    • Marked as answer by jessica2030 Monday, February 22, 2016 3:09 AM
    Sunday, February 21, 2016 8:32 PM

All replies