25
votes

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?

7
When you do construction initialization the way you show, the default constructor runs (initializing ServiceUrl to its default value (which, for strings, is null)). Then, the initialize statement runs. If you want it non-nullable, it needs to exit all constructors initializedFlydog57
POCO doesn't mean it has no constructor or that the properties aren't initialized. It means Plain Old C# Object. Just an object like any other, without inheriting from any special class. I suspect you have a different question. How to create DTOs - Data Transfer ObjectsPanagiotis Kanavos
This should be the responsibility of the one initializing the class to ensure that the properties are non-null the class should be in a valid state always. If null isn't allowed, the property should never be null. Perhaps, instead of a basic string you should use a specialized class for the URL that can have a value of None or` Missing`, like the Option class in F#. C# 8 allows you to write such classes and check them with pattern matchingPanagiotis Kanavos
@Panagiotis Kanavos, The class,in my case, has a constraint to be parameter-less Constructor. So I have to use Property Initializer: public string ServiceUrl { get; set; } = default! ;. I hope Roslyn may have in the future a way to handle Late initialization outside the scope of ctor. I was using MayBe<T> (like Option class), but I switched to nullable Reference Type in c#8 for the new code.M.Hassan
NRTs aren't Maybes, in fact, Maybes are now even more important and easier to use. Provided of course they're build using C# idioms that make them easy to work with pattern matchingPanagiotis Kanavos

7 Answers

32
votes

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));
    }
    
9
votes

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.

3
votes

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.

3
votes

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 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"
};

Also let's consider your class like this

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

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

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

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.

1
votes

The benefit of Nullable reference types is to manage null reference exceptions effectively. So it is better to use the directive #nullable enable. It helps developers to avoid null reference exceptions at run time.

How it helps to avoid null reference exceptions: The below 2 things compiler will make sure during static flow analysis.

  1. The variable has been definitely assigned to a non-null value.
  2. The variable or expression has been checked against null before de-referencing it.

If does not satisfy the above conditions, compiler will throw warnings. Note : All these activities emitted during compile time.

What is the special in null reference types:

After C# 8.0, reference types are considered as non nullable. So that compiler throw timely warnings if the reference type variables are not handle the nulls properly.

What we can do, if we know that reference variables are NULLABLE:

  1. Appended '?' before the variable (Example) string? Name
  2. Using "null forgiving operator" (Example) string Name {get;set;} = null!; or string Name {get;set;} = default!;
  3. Using "backing fields" (Example):

    private string _name; public string Name {get { return _name; } set {_name = value;} }

What we can do, if we know that reference variables are NON-NULLABLE:

If it is non nullable initialize the property using constructors.

Benefits of non-nullable reference types:

  1. Better handling of null reference exceptions
  2. With the help of compile time warnings, developers can correct their code timely.
  3. Developers will convey the intent to compiler while design the class. Thereafter compiler will enforce the intent through out the code.
1
votes

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
-1
votes

To get rid of the warnings on DTOs, at the start of the DTO's cs file, specify: #pragma warning disable CS8618

And at the end: #pragma warning restore CS8618