diff --git a/Bson/DefaultSerializer/Serializers/EnumSerializer.cs b/Bson/DefaultSerializer/Serializers/EnumSerializer.cs index 0ba26dd7b7e..60225c532e6 100644 --- a/Bson/DefaultSerializer/Serializers/EnumSerializer.cs +++ b/Bson/DefaultSerializer/Serializers/EnumSerializer.cs @@ -105,7 +105,13 @@ private void VerifySerializeTypes( Type nominalType, Type actualType ) { - if (nominalType != typeof(object) && nominalType != actualType) { + // problem is that the actual type of a nullable type that is not null will appear as the non-nullable type + // we want to allow both Enum and Nullable here + bool isNullableOfActual = ( + nominalType.GetGenericTypeDefinition() == typeof(Nullable<>) + && nominalType.GetGenericArguments().FirstOrDefault() == actualType + ); + if (nominalType != typeof(object) && nominalType != actualType && (!isNullableOfActual)) { var message = string.Format("EnumSerializer.Serialize cannot be used with nominal type: {0}", nominalType.FullName); throw new BsonSerializationException(message); } diff --git a/BsonUnitTests/DefaultSerializer/Serializers/NullableTypeSerializerTests.cs b/BsonUnitTests/DefaultSerializer/Serializers/NullableTypeSerializerTests.cs index 52241698298..073fbb706e2 100644 --- a/BsonUnitTests/DefaultSerializer/Serializers/NullableTypeSerializerTests.cs +++ b/BsonUnitTests/DefaultSerializer/Serializers/NullableTypeSerializerTests.cs @@ -38,6 +38,8 @@ private class C { public int? Int32 { get; set; } public long? Int64 { get; set; } public ObjectId? ObjectId { get; set; } + [BsonRepresentation(BsonType.String)] + public ConsoleColor? Enum { get; set; } // public Struct? Struct { get; set; } } @@ -54,7 +56,8 @@ private class C { "'Guid' : null, " + "'Int32' : null, " + "'Int64' : null, " + - "'ObjectId' : null" + + "'ObjectId' : null, " + + "'Enum' : null" + // "'Struct' : null" + " }"; @@ -118,6 +121,18 @@ public void TestDouble() { Assert.IsTrue(bson.SequenceEqual(rehydrated.ToBson())); } + [Test] + public void TestEnum() + { + C c = new C { Enum = ConsoleColor.Red}; + var json = c.ToJson(); + var expected = template.Replace("'Enum' : null", "'Enum' : \"Red\"").Replace("'", "\""); + Assert.AreEqual(expected, json); + + var bson = c.ToBson(); + var rehydrated = BsonSerializer.Deserialize(bson); + Assert.IsTrue(bson.SequenceEqual(rehydrated.ToBson())); + } [Test] public void TestGuid() { C c = new C { Guid = Guid.Empty };