At runtime, how can I test whether a Property is readonly?

With PropertyDescriptor, check IsReadOnly.

With PropertyInfo, check CanWrite (and CanRead, for that matter).

You may also want to check [ReadOnly(true)] in the case of PropertyInfo (but this is already handled with PropertyDescriptor):

 ReadOnlyAttribute attrib = Attribute.GetCustomAttribute(prop,
       typeof(ReadOnlyAttribute)) as ReadOnlyAttribute;
 bool ro = !prop.CanWrite || (attrib != null && attrib.IsReadOnly);

IMO, PropertyDescriptor is a better model to use here; it will allow custom models.


I noticed that when using PropertyInfo, the CanWrite property is true even if the setter is private. This simple check worked for me:

bool IsReadOnly = prop.SetMethod == null || !prop.SetMethod.IsPublic;

Also - See Microsoft Page

using System.ComponentModel;

// Get the attributes for the property.

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

// Check to see whether the value of the ReadOnlyAttribute is Yes.
if(attributes[typeof(ReadOnlyAttribute)].Equals(ReadOnlyAttribute.Yes)) {
   // Insert code here.
}

Tags:

C#

Properties