@@ -76,35 +76,37 @@ of the ``BsonSerializer`` class as follows:
7676Custom Serializers
7777~~~~~~~~~~~~~~~~~~
7878
79- In some cases, you might need to create a custom serializer. When creating a
80- custom serializer, implement the ``SerializerBase<T>`` abstract base class and
81- override the ``Deserialize()`` and ``Serialize()`` methods.
79+ To create your own custom serializer, implement the ``IBsonSerializer`` base class, set
80+ the ``ValueType`` member, and override the ``Deserialize()`` and ``Serialize()`` methods.
8281
8382The following code example shows a custom ``BsonRegularExpression`` serializer:
8483
8584.. code-block:: csharp
8685
87- class CustomRegularExpressionSerializer : SerializerBase<Regex>
86+ class CustomRegularExpressionSerializer : IBsonSerializer
8887 {
89- public override Regex Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
90- {
91- var type = context.Reader.GetCurrentBsonType();
88+ public Type ValueType => typeof(Regex);
89+
90+ public object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
91+ {
92+ var type = context.Reader.CurrentBsonType;
9293 switch (type)
9394 {
94- case BsonType.RegularExpression:
95- return context.Reader.ReadRegularExpression().AsRegex;
96- case BsonType.String:
97- var pattern = context.Reader.ReadString();
98- return new Regex(pattern);
99- default:
100- throw new NotSupportedException($"Cannot convert a {type} to a RegularExpression.");
95+ case BsonType.RegularExpression:
96+ return context.Reader.ReadRegularExpression().AsRegex;
97+ case BsonType.String:
98+ var pattern = context.Reader.ReadString()
99+ return new Regex(pattern);
100+ default:
101+ throw new NotSupportedException($"Cannot convert a {type} to a RegularExpression.");
101102 }
102- }
103-
104- public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Regex value)
105- {
106- context.Writer.WriteRegularExpression(value);
107- }
103+ }
104+
105+ public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
106+ {
107+ var regex = (Regex) value;
108+ context.Writer.WriteRegularExpression(regex);
109+ }
108110 }
109111
110112Opt-in Interfaces
@@ -155,4 +157,3 @@ guide, see the following API documentation:
155157- `SerializerRegistry <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.BsonSerializer.SerializerRegistry.html>`__
156158- `BsonSerializer <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.BsonSerializer.html>`__
157159- `IBsonSerializer <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.IBsonSerializer.html>`__
158- - `SerializerBase<T> <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.Serializers.SerializerBase-1.html>`__
0 commit comments