Search code examples
c#nullable

C# Nullable List


Are all the following valid ? They are properties of a class instantiated to _s.

    public List<int>? _Int1 { get; set; }
    public List<int?> _Int2 { get; set; }
    public List<Nullable<int>> _Int3 { get; set; }

I've tried all of them and it all work. However, when I assign the value, it has to match the exact way it was defined, ie:

        _s._Int1 = new List<int> { 0 } ;
        _s._Int2 = new List<int?> { 0 };
        _s._Int3 = new List<Nullable<int>> { 0 };

If I were to assign differently, then I get the following:

        _s._Int1 = new List<int?> { 0 } ;                   // fail
        _s._Int2 = new List<Nullable<int>> { 0 };           // OK
        _s._Int3 = new List<int?> { 0 };                    // OK

My questions is what is the correct way to declare a Nullable. Thanks.


Solution

  • Please, note that T? can mean two different things:

    1. If T is struct, then T? is Nullable<T>
    2. If T is class then T? means nullable reference type, it means that the instance is not supposed to be null

    PLease, see https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references for details

    In your question int? is a case #1, since int is a struct, when List<int?> is a case #2, since List<T> is a class:

    // _Int1 is List<int>
    // _Int1 can be null
    public List<int>? _Int1 { get; set; } 
    
    // _Int2 is List<Nullable<int>>
    // _Int2 is not supposed to be null
    public List<int?> _Int2 { get; set; }
    
    // Longer version of _Int2 type declaration
    // _Int3 is List<Nullable<int>>
    // _Int3 is not supposed to be null
    public List<Nullable<int>> _Int3 { get; set; }