Best practice when using C# 8.0 nullable reference types with deserialization?

后端 未结 3 1971
长发绾君心
长发绾君心 2021-01-15 03:36

I am trying C# 8.0 out, and I want to enable the null reference checking for the entire project. I am hoping I can improve my code design, and without disabling the nullabil

3条回答
  •  忘掉有多难
    2021-01-15 04:09

    If I understand correctly, your question boils down to:

    How do I avoid compiler warnings

    CS8618: Non-nullable property 'Name' is uninitialized. Consider declaring the property as nullable.

    for simple model classes which are used for serialization?

    You can solve the problem by creating a default constructor for which you suppress the warning. Now you want to make sure that this constructor is only used by your deserialization routine (e.g. System.Text.Json or Entity Framework). To avoid unintentional use add annotation [Obsolete] with parameter error=true which would raise compiler error CS0618.

    As code:

    public class PersonForSerialize
    {
    #pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
        [Obsolete("Only intended for de-serialization.", true)]
        public PersonForSerialize()
    #pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
        {
        }
    
        // Optional constructor
        public PersonForSerialize(string name, IReadOnlyList friends)
        {
            Name = name;
            Friends = friends;
        }
    
        public string Name { get; set; }
        public IReadOnlyList Friends { get; set; }
    }
    

    Note1: You can let Visual Studio auto-generate the optional constructor using a quick action.

    Note2: If you really mean to use the constructor marked as obsolete, you need to remove the error=true parameter. Now you can suppress the warning when calling the parameter-less constructor via #pragma warning disable CA1806.

提交回复
热议问题