[CSHARP-2414] Enum Deserializer Issue with BsonType.String Created: 11/Oct/18  Updated: 27/Oct/23  Resolved: 11/Oct/18

Status: Closed
Project: C# Driver
Component/s: BSON
Affects Version/s: 2.7.0
Fix Version/s: None

Type: Improvement Priority: Major - P3
Reporter: Sun Yu Assignee: Robert Stam
Resolution: Works as Designed Votes: 0
Labels: EnumSerializer
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

In the source code of c# Driver v2.7,

namespace MongoDB.Bson.Serialization.Serializers
{
    public class EnumSerializer<TEnum> : StructSerializerBase<TEnum>, IRepresentationConfigurable<EnumSerializer<TEnum>> where TEnum : struct
    {
      ......
      public override TEnum Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
      {
        var bsonReader = context.Reader;
 
        var bsonType = bsonReader.GetCurrentBsonType();
        switch (bsonType)
        {
            ......
            case BsonType.String: return (TEnum)Enum.Parse(typeof(TEnum), bsonReader.ReadString());
            default:
                throw CreateCannotDeserializeFromBsonTypeException(bsonType);
        }
      }
     ......
    }
}

In this method, the code

case BsonType.String: return (TEnum)Enum.Parse(typeof(TEnum), bsonReader.ReadString());

will throw an ArgumentException when the ReadString() returns a value that is not defined in the TEnum type.



 Comments   
Comment by Sun Yu [ 11/Oct/18 ]

I see. Thank you for your guiding.

Comment by Robert Stam [ 11/Oct/18 ]

This behavior is by design.

If a document being read from the database (i.e. being deserialized) cannot be properly represented in C# it is better to throw an exception than to silently ignore the problem and lose information.

If you actually want your serializer to behave this way you can always write your own serializer and register it to be used instead of the built-in one, but the built-in one must continue to behave this way.

Generated at Wed Feb 07 21:42:29 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.