Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforce REAL non-nullable string reference type

Tags:

I've just tried the new C# 8 Nullable Reference Type, which allows us to use non-nullable strings.

In my .csproj (.NET Core 3.1) I set this:

<Nullable>enable</Nullable>

I created a FooClass as follows:

public class FooClass
{
    public FooClass(string testString, DateTime testDate)
    {
        if (testString == null || testString == string.Empty)
            throw new ArgumentNullException(nameof(testString));
        else if (testDate == null)
            throw new ArgumentNullException(nameof(testDate));

        MyString = testString;
        MyDate = testDate;
    }

    public string MyString { get; }
    public DateTime MyDate { get; }
}

However, when I create a new instance of my class in my Main() with null values on purpose:

var test = new FooClass(testString:null, testDate:null);

The compiler is fine with the testString parameter, but with the testDate parameter it tells me:

Argument 2: cannot convert from '<null>' to 'DateTime'

How can I get the same behavior for the first argument?

My testString parameter is a non-nullable reference type, just like testDate. As I didn't declare it as string?, I'm expecting the compiler to behave the same way for both parameters.

Is there another feature to activate to enforce real non-nullable strings in C#?

like image 463
Jérôme MEVEL Avatar asked Jan 27 '20 09:01

Jérôme MEVEL


1 Answers

You can add TreatWarningsAsErrors option to your csproj file

<TreatWarningsAsErrors>true</TreatWarningsAsErrors>

or add CS8625 warning to WarningsAsErrors list

<WarningsAsErrors>NU1605;CS8625</WarningsAsErrors>

And this code will generate an expected error

var test = new FooClass(testString: null, testDate: default);

error CS8625: Cannot convert null literal to non-nullable reference type.

Nullable reference types are implemented as type annotations in CLR, this can be a reason that compiler shows you an error with testDate in your original sample first.

var test = new FooClass(testString: null, testDate: null);

When you get rid of this error, you'll see the expected behavior with nullable references errors/warnings

like image 198
Pavel Anikhouski Avatar answered Oct 27 '22 10:10

Pavel Anikhouski