At runtime, how can I check if a property is read-only?

I create automatically generated code that creates a winform dialog based on the configuration (text fields, dateTimePickers, etc.). The controls in these dialogs are populated from the saved dataset and

it is necessary to set and get properties for various control objects (custom or others).

//Upon opening of form - populate control properties with saved values MyObject.Value = DataSource.GetValue("Value"); //Upon closing of form, save values of control properties to dataset. DataSource.SetValue("Value") = MyObject.Value; 

Now everything is fine, but what of the readOnly properties? I want to save the result of a property, but you need to know when to NOT generate code that will try to populate it.

 //Open form, attempt to populate control properties. //Code that will result in 'cannot be assigned to -- it is read only' MyObject.HasValue = DataSource.GetValue("HasValue"); MyObject.DerivedValue = DataSource.GetValue("Total_SC2_1v1_Wins"); //Closing of form, save values. DataSource.SetValue("HasValue") = MyObject.HasValue; 

Remember that I do not know the type of object that I created before execution.

How can I (at runtime) identify the readonly property?

+6
c # properties
source share
3 answers

Use PropertyDescriptor to select the IsReadOnly check box.

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

You can also check [ReadOnly(true)] in the case of PropertyInfo (but this is already being handled using PropertyDescriptor ):

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

IMO, PropertyDescriptor is the best model to use here; this will allow you to customize models.

+5
source share

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; 
+2
source share

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. } 
+1
source share

All Articles