Nullable reference type in C#8 when using DTO classes with an ORM

14,414

Solution 1

You can do either of the following:

  1. EF Core suggests initializing to null! with null-forgiving operator

    public string ServiceUrl { get; set; } = null! ;
    //or
    public string ServiceUrl { get; set; } = default! ;
    
  2. Using backing field:

    private string _ServiceUrl;
    public string ServiceUrl
    {
        set => _ServiceUrl = value;
        get => _ServiceUrl
               ?? throw new InvalidOperationException("Uninitialized property: " + nameof(ServiceUrl));
    }
    

Solution 2

If it's non nullable, then what can the compiler do when the object is initialized?

The default value of the string is null, so you will

  1. either need to assign a string default value in the declaration

    public string ServiceUrl { get; set; } = String.Empty;

  2. Or initialize the value in the default constructor so that you will get rid of the warning

  3. Use the ! operator (that you can't use)

  4. Make it nullable as robbpriestley mentioned.

Solution 3

I've been playing with the new Nullable Reference Types (NRT) feature for a while and I must admit the biggest complain I've is that the compiler is giving you those warnings in the classes' declarations.

At my job I built a micro-service trying to solve all those warnings leading to quite a complicated code especially when dealing with EF Core, AutoMapper and DTOs that are shared as a Nuget package for .NET Core consumers. This very simple micro-service quickly became a real mess just because of that NRT feature leading me to crazy non-popular coding styles.

Then I discovered the awesome SmartAnalyzers.CSharpExtensions.Annotations Nuget package after reading Cezary Piątek's article Improving non-nullable reference types handling.

This Nuget package is shifting the non-nullbable responsibility to the caller code where your objects are instantiated rather than the class declaration one.

In his article he is saying we can activate this feature in the whole assembly by writing the following line in one of your .cs files

[assembly: InitRequiredForNotNull]

You could put it in your Program.cs file for example but I personally prefer to activate this in my .csproj directly

<ItemGroup>
    <AssemblyAttribute Include="SmartAnalyzers.CSharpExtensions.Annotations.InitRequiredForNotNullAttribute" />
</ItemGroup>

Also I changed the default CSE001 Missing initialization for properties errors to warnings by setting this in my .editorconfig file

[*.cs]
dotnet_diagnostic.CSE001.severity = warning

You can now use your Connection class as you'd normally do without having any error

var connection = new Connection()
{
    ServiceUrl = "ServiceUrl"
};

Just one thing to be aware of. Let's consider your class like this

public class Connection
{
    public string ServiceUrl { get; }
    public string? UserName { get; }
    public string? Password { get; }

    public Connection(string serviceUrl, string? userName = null, string? password = null)
    {
        if (string.IsNullOrEmpty(serviceUrl))
            throw new ArgumentNullException(nameof(serviceUrl));

        ServiceUrl = serviceUrl;
        UserName = userName;
        Password = password;
    }
}

In that case when you instantiate your object like

var connection = new Connection("serviceUrl");

The SmartAnalyzers.CSharpExtensions.Annotations Nuget package isn't analyzing your constructor to check if you're really initializing all non-nullable reference types. It's simply trusting it and trusting that you did things correctly in the constructor. Therefore it's not raising any error even if you forgot a non-nullable member like this

public Connection(string serviceUrl, string? userName = null, string? password = null)
{
    if (string.IsNullOrEmpty(serviceUrl))
        throw new ArgumentNullException(serviceUrl);

    UserName = userName;
    Password = password;
}

I hope you will like the idea behind this Nuget package, it had become the default package I install in all my new .NET Core projects.

Solution 4

Another thing that might come handy in some scenarios:

[SuppressMessage("Compiler", "CS8618")]

Can be used on top of member or whole type.


Yet another thing to consider is adding #nullable disable on top of file to disable nullable reference for the whole file.

Solution 5

Usually DTO classes are stored in separate folders, so I simply disable this diagnostic in .editorconfig file based on path pattern:

[{**/Responses/*.cs,**/Requests/*.cs}]
# CS8618: Non-nullable field is uninitialized. Consider declaring as nullable.
dotnet_diagnostic.CS8618.severity = none
Share:
14,414
M.Hassan
Author by

M.Hassan

Qualification: Master Degree in computer science. Diploma in Information technology. Certification: MCTS , MCITP in C# Web/Forms and SqlServer developer/administration Experience: Development: C#- Vb.net- Matlab, Python- java -REST/Web API- TSQl- PL/Sql-Powershell Database: Sql Server- Oracle Software Engineering: Agile- TDD - Design Pattern Version Control (GIT) Author of open source project site in: OData2Poco

Updated on June 27, 2022

Comments

  • M.Hassan
    M.Hassan almost 2 years

    I activated this feature in a project having data transfer object (DTO) classes, as given below:

    public class Connection
        {
            public string ServiceUrl { get; set; }
            public string? UserName { get; set; }
            public string? Password { get; set; }
            //... others 
        }
    

    But I get the error:

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

    This is a DTO class, so I'm not initializing the properties. This will be the responsibility of the code initializing the class to ensure that the properties are non-null.

    For example, the caller can do:

    var connection = new Connection
    {
      ServiceUrl=some_value,
      //...
    }
    

    My question: How to handle such errors in DTO classes when C#8's nullability context is enabled?