PropertyInfo.CanWrite Property
Gets a value indicating whether the property can be written to.
Assembly: mscorlib (in mscorlib.dll)
The following example defines two properties. The first property is writable and the CanWrite property is true. The second property is not writable (there is no set accessor), and the CanWrite property is false.
using System; using System.Reflection; // Define one writable property and one not writable. public class Mypropertya { private string caption = "A Default caption"; public string Caption { get{return caption;} set {if(caption!=value) {caption = value;} } } } public class Mypropertyb { private string caption = "B Default caption"; public string Caption { get{return caption;} } } class Mypropertyinfo { public static int Main() { Console.WriteLine("\nReflection.PropertyInfo"); // Define two properties. Mypropertya Mypropertya = new Mypropertya(); Mypropertyb Mypropertyb = new Mypropertyb(); // Read and display the property. Console.Write("\nMypropertya.Caption = " + Mypropertya.Caption); Console.Write("\nMypropertyb.Caption = " + Mypropertyb.Caption); // Write to the property. Mypropertya.Caption = "A- No Change"; // Mypropertyb.Caption cannot be written to because // there is no set accessor. // Read and display the property. Console.Write("\nMypropertya.Caption = " + Mypropertya.Caption); Console.Write ("\nMypropertyb.Caption = " + Mypropertyb.Caption); // Get the type and PropertyInfo. Type MyTypea = Type.GetType("Mypropertya"); PropertyInfo Mypropertyinfoa = MyTypea.GetProperty("Caption"); Type MyTypeb = Type.GetType("Mypropertyb"); PropertyInfo Mypropertyinfob = MyTypeb.GetProperty("Caption"); // Get and display the CanWrite property. Console.Write("\nCanWrite a - " + Mypropertyinfoa.CanWrite); Console.Write("\nCanWrite b - " + Mypropertyinfob.CanWrite); return 0; } }
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
The explanation of this property isn't complete. It doesn't guarantee that the property is writable, it only tells, that the property has a setter.
To check, if the property can be written you have to additionally distinguish, if the property setter is public or not. To check, if the public setter is present use "GetSetMethod" method. So, to check property for public setter use following snippet:
bool hasPublicSetter = propertyInfo.IsWritable && propertyInfo.GetSetMethod() != null;
- 5/30/2012
- Jiri Pokorny