Skip to content

WithEnforceNullabilty() has unpredictable behavior with classes having both nullable reference type and value type #1018

Description

@popemkt

Describe the bug

When deserializing to a class with both nullable reference and value types members, YamlDotNet considers the nullabe value type to not accept null values.

I suspect it's coming from the reflection checks only checking if a member allows null using the presence of NullableAttribute, which fails if it's a TValueType? (this won't generate a NullableAttribute). But I've seen strange cases where the compiler doesn't even generate NullableAttribute on a reference type, so I won't be too sure about that.

To Reproduce
Using latest version: 16.2.1

Create a new console project with .net8
Program.cs

#nullable enable
using YamlDotNet.Serialization;

var deserializer = new DeserializerBuilder().WithEnforceNullability().Build();
var yaml = @"
TestString: null
TestBool: null
";
var test = deserializer.Deserialize<NonNullableClass>(yaml);

public class NonNullableClass
{
    public string? TestString { get; set; }
    public bool? TestBool { get; set; }
}

Result:

Unhandled exception. (Line: 2, Col: 1, Idx: 2) - (Line: 2, Col: 11, Idx: 12): Strict nullability enforcement error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions