Why don't I get a warning about possible dereference of a null in C# 8 with a class member of a struct?

前端 未结 2 1239
予麋鹿
予麋鹿 2020-12-11 02:47

In a C# 8 project with nullable reference types enabled, I have the following code which I think should give me a warning about a possible null dereference, but doesn\'t:

2条回答
  •  再見小時候
    2020-12-11 03:22

    In the light of the excellent answer by @peter-duniho it seems that as of Oct-2019 it's best to mark all non-value-type members a nullable reference.

    #nullable enable
    public class C
    {
        public int P1 { get; } 
    }
    
    public struct S
    {
        public C? Member { get; } // Reluctantly mark as nullable reference because
                                  // https://devblogs.microsoft.com/dotnet/nullable-reference-types-in-csharp/
                                  // states:
                                  // "Using the default constructor of a struct that has a
                                  // field of nonnullable reference type. This one is 
                                  // sneaky, since the default constructor (which zeroes 
                                  // out the struct) can even be implicitly used in many
                                  // places. Probably better not to warn, or else many
                                  // existing struct types would be rendered useless."
    }
    
    public class Program
    {
        public static void Main()
        {
            var instance = new S();
            Console.WriteLine(instance.Member.P1); // Warning
        }
    }
    

提交回复
热议问题