Compartilhar via


Using ShouldSerialize Methods

The ShouldSerializeXXX method, where XXX is replaced by the name of the property, is a method that returns a Boolean value informing the serializer whether a property has changed from its default value. Inside the method you can define an appropriate default value. For example, if you defined a custom property called width, your code would read as follows:

public bool ShouldSerializeWidth()
{
       // If width is not default value of 100, return true so the value gets serialized
       return _width != 100;
}

There are three cases in which you should provide a ShouldSerializeXXX method for your custom properties:

  • If you define a custom property that uses a complex type (the DefaultValue attribute can only be used for simple types).

  • If you expect others to derive from your WebPart class.

    By providing a ShouldSerializeXXX method, you enable derived classes to override the default.

  • If you want your property to be accessible by the Web Part Page Services Component (WPSC).

The ShouldSerializeXXX method works for both complex and simple types, and overrides the constructor comparison. (If your custom property uses simple types, you can use the DefaultValue attribute. For more information, see Using the DefaultValue Attribute for Custom Properties.)

Note  You must provide either the DefaultValue attribute or the ShouldSerializeXXX method for your Web Part custom properties. If neither is found, an exception is raised.

For more information about working with custom properties in Web Parts, see Creating a Web Part with Custom Properties. For more information about the ShouldSerialize method, see the .NET Framework Developer's Guide on MSDN®, the Microsoft Developer Network.

Note  The ShouldSerializeXXX methods were called ShouldPersistXXX methods in .NET Beta 2.