ShouldPersist and Reset are optional methods that you can provide for a property that you define, if the property does not a have simple default value. If the property has a simple default value, you should apply the DefaultValueAttribute and supply the default value to the attribute class constructor instead. Either of these mechanisms enable the following features in the designer:
Note You should either apply the DefaultValueAttribute or provide Reset<PropertyName> and ShouldPersist<PropertyName> methods, but not both.
The Reset<PropertyName> methods causes a property to be set to its default value as shown below.
[C#] public void ResetFont() { Font = null; }
Note If a property has neither a Reset method defined, nor a DefaultValueAttribute, nor a default value supplied in its declaration, the reset setting for that property will be grayed in the context menu of the property browser of the Win Forms designer of Visual Studio.
The ShouldPersist<PropertyName> is used by a designer such as Visual Studio to check if a property has changed from its default value. Code is written into the form only if a property is changed, thus allowing for more efficient code generation. For example:
[C#] //Returns true if the font has changed and false otherwise. //Code will be written to the form only if true is returned. public bool ShouldPersistFont() { return thefont != null; }
A complete code example is given below.
[C#] using System; using System.WinForms; using System.Drawing; public class MyControl : RichControl { //Declare an instance of Font //and set its default value to null. //You do not have to use the fully qualified name //because the using System.Drawing.Font declaration //is used. private Font thefont = null; public Font Font { //Note that the Font property never //returns null. // get { if (thefont != null) return thefont; if (Parent != null) return Parent.Font; return Fonts.DefaultGui; } set { thefont = value; } } public bool ShouldPersistFont() { return thefont != null; } public void ResetFont() { Font = null; } }
This example also shows how ambient properties are implemented in Win Forms. In this case, even though the default value of the private variable accessed by the Font property is null, the property browser will never display null, but the Font property of the parent (if non-null), or the default Font for controls. Thus the default value for Font is not "simple", and a DefaultValueAttribute cannot be applied. Instead, the ResetFont and ShouldPersistFont methods must be implemented.