Remove C# attribute of a property dynamically

SysAdmin picture SysAdmin · Mar 20, 2010 · Viewed 61k times · Source

I have a class with a set of properties As given below.

class ContactInfo
{
    [ReadOnly(true)]
    [Category("Contact Info")]
    public string Mobile { get; set; }

    [Category("Contact Info")]
    public string Name{ get; set; }
}

The objects of this class is being assigned to a property grid, so that the users can update an existing contact. you can see that Mobile is marked as ReadOnly.

But, when I want to add an entirely new Contact, I would want the users to be able to edit the contact Mobile also. For that I need to remove the Readonly property dynamically from the Type, before assigning the object to the property grid. Is it possible?

Answer

andreialecu picture andreialecu · Mar 20, 2010

You can not remove the attribute at runtime, but you can use reflection to change the ReadOnly attribute's ReadOnly private backing field to False. Making it the equivalent of [ReadOnly(false)]

See this article for details:

http://codinglight.blogspot.com/2008/10/changing-attribute-parameters-at.html

Edit: fixed link