MongoDB.Bson.Serialization.Serializers.SByteSerializer.Deserialize C# (CSharp) Method

Deserialize() public method

Deserializes an object from a BsonReader.
public Deserialize ( MongoDB.Bson.IO.BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options ) : object
bsonReader MongoDB.Bson.IO.BsonReader The BsonReader.
nominalType System.Type The nominal type of the object.
actualType System.Type The actual type of the object.
options IBsonSerializationOptions The serialization options.
return object
        public override object Deserialize(
            BsonReader bsonReader,
            Type nominalType,
            Type actualType,
            IBsonSerializationOptions options)
        {
            VerifyTypes(nominalType, actualType, typeof(sbyte));

            var bsonType = bsonReader.GetCurrentBsonType();
            var lostData = false;
            sbyte value;
            switch (bsonType)
            {
                case BsonType.Binary:
                    var bytes = bsonReader.ReadBytes();
                    if (bytes.Length != 1)
                    {
                        throw new Exception("Binary data for SByte must be exactly one byte long.");
                    }
                    value = (sbyte)bytes[0];
                    break;
                case BsonType.Int32:
                    var int32Value = bsonReader.ReadInt32();
                    value = (sbyte)int32Value;
                    lostData = (int)value != int32Value;
                    break;
                case BsonType.Int64:
                    var int64Value = bsonReader.ReadInt64();
                    value = (sbyte)int64Value;
                    lostData = (int)value != int64Value;
                    break;
                case BsonType.String:
                    var s = bsonReader.ReadString();
                    if (s.Length == 1)
                    {
                        s = "0" + s;
                    }
                    value = (sbyte)byte.Parse(s, NumberStyles.HexNumber);
                    break;
                default:
                    var message = string.Format("Cannot deserialize SByte from BsonType {0}.", bsonType);
                    throw new Exception(message);
            }
            if (lostData)
            {
                var message = string.Format("Data loss occurred when trying to convert from {0} to SByte.", bsonType);
                throw new Exception(message);
            }

            return value;
        }