Skip to content

Commit

Permalink
Merge pull request #621 from pensono/nullable-struct
Browse files Browse the repository at this point in the history
+semver:fix Fix nullable struct serialization
  • Loading branch information
aaubry authored Jun 28, 2021
2 parents 78a57da + 78ff21e commit 665b182
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
5 changes: 5 additions & 0 deletions YamlDotNet.Test/Serialization/SerializationTestHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,11 @@ public enum EnumExample
Two
}

public struct StructExample
{
public int Value { get; set; }
}

public enum SByteEnum : sbyte { Default, Sbyte }
public enum ByteEnum : byte { Default, Byte }
public enum Int16Enum : short { Default, Short }
Expand Down
18 changes: 18 additions & 0 deletions YamlDotNet.Test/Serialization/SerializationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,24 @@ public void RoundtripNullableEnums(EnumExample? value)
result.Should().Be(value);
}

[Fact]
public void RoundtripNullableStructWithValue()
{
var value = new StructExample { Value = 2 };

var result = DoRoundtripFromObjectTo<StructExample?>(value);

result.Should().Be(value);
}

[Fact]
public void RoundtripNullableStructWithoutValue()
{
var result = DoRoundtripFromObjectTo<StructExample?>(null);

result.Should().Be(null);
}

[Fact]
public void SerializeCircularReference()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,14 @@ bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func<IPars
return false;
}

value = objectFactory.Create(expectedType);
// Strip off the nullable type, if present. This is needed for nullable structs.
var implementationType = Nullable.GetUnderlyingType(expectedType) ?? expectedType;

value = objectFactory.Create(implementationType);
while (!parser.TryConsume<MappingEnd>(out var _))
{
var propertyName = parser.Consume<Scalar>();
var property = typeDescriptor.GetProperty(expectedType, null, propertyName.Value, ignoreUnmatched);
var property = typeDescriptor.GetProperty(implementationType, null, propertyName.Value, ignoreUnmatched);
if (property == null)
{
parser.SkipThisAndNestedEvents();
Expand Down

0 comments on commit 665b182

Please sign in to comment.