Skip to content

Should Serializes

kevin-montrose edited this page Apr 10, 2021 · 6 revisions

ShouldSerializes

Introduction

The ShouldSerialize class represents a callback that occurs prior to serializing a member into a cell, and allows suppression decisions to be made on a per-row basis. ShouldSerializes are only used during static serialization.

The name is taken from the ShouldSerializeXXX() pattern introduced by Windows Forms, and adopted by other serializers in the .NET world (like System.XML, and protobuf-net).

Supported Backers

ShouldSerialize instances can be backed by methods, and delegates.

Delegates

A ShouldSerialize may be backed by two different types of delegates:

  • delegates of the form bool Name(in WriteContext)
  • delegates of the form bool Name(RowType, in WriteContext)

They differ by whether or not they take the row being serialized as a parameter.

If a delegate backing a ShouldSerialize returns false, the associated member will not be written for the current row.

Cesil provides StaticShouldSerializeDelegate, ShouldSerializeDelegate<TRow> and ShouldSerialize.ForDelegate<...>(...)) overloads which conform to these forms. You can also explicitly cast any delegate to a ShouldSerialize, provided it is logically equivalent to StaticShouldSerializeDelegate or ShouldSerializeDelegate<TRow>.

Methods

A ShouldSerialize can be backed by many different kinds of MethodInfo.

All supported methods must have a boolean return.

A static method:

  • have zero parameters or
  • have one parameter of the row type or
  • have one parameter of type in WriteContext or
  • have two parameters, the first of the row type and the second of type in WriteContext

An instance method must:

  • be on the row type and take zero parameters or
  • be on the row type and take one parameter of type in WriteContext

Use the ShouldSerialize.ForMethod(MethodInfo) method to create a ShouldSerialize backed by a method. You can also explicitly cast any MethodInfo to a ShouldSerialize, provided it follows the above rules.

Explicit Casts

Cesil provides explicit casts of MethodInfo, and Delegate to ShouldSerialize. These are roughly equivalent to calling the static ForXXX(...) methods on ShouldSerialize, but differ by allowing null values.

Clone this wiki locally