Issue with nullable reference types in C# 8

55 Views Asked by At

I'm currently working on upgrading my project to C# 8, specifically interested in leveraging nullable reference types to enhance code safety. However, I'm encountering some unexpected behavior that I'm struggling to understand.

using System;

namespace NullableReferenceTypesDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string? nullableString = null;
            string nonNullableString = "Hello";

            // This line should ideally throw a warning due to the nullability of nullableString
            Console.WriteLine(nullableString.Length);

            // This line should ideally not throw a warning
            Console.WriteLine(nonNullableString.Length);
        }
    }
}

I expect the compiler to issue a warning on the line where nullableString.Length is accessed, but it seems like it's not recognizing the nullability of nullableString in this case.

I've ensured that my project is targeting C# 8 and that nullable reference types are enabled (<Nullable>enable</Nullable> in the .csproj file). Is there something I'm missing here, or is this a bug with nullable reference types in C# 8?.

1

There are 1 best solutions below

0
Arsen Belluyan On

Thanks for the comment-answer, yeah Adding <NullableWarnings>true</NullableWarnings> in the .csproj file helps me. It appears that even if the <Nullable>enable</Nullable> compiler setting is not issuing warnings by default, adding this NullableWarnings tag resolves the issue.