Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion Bson/DefaultSerializer/Serializers/EnumSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Enum> 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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
}

Expand All @@ -54,7 +56,8 @@ private class C {
"'Guid' : null, " +
"'Int32' : null, " +
"'Int64' : null, " +
"'ObjectId' : null" +
"'ObjectId' : null, " +
"'Enum' : null" +
// "'Struct' : null" +
" }";

Expand Down Expand Up @@ -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<C>(bson);
Assert.IsTrue(bson.SequenceEqual(rehydrated.ToBson()));
}
[Test]
public void TestGuid() {
C c = new C { Guid = Guid.Empty };
Expand Down