Search code examples
c#nullable-reference-types

List<T> is non nullable?


Using VS 2022, .Net 6.0, I thought this was correct :

public static void test(List<String> list = null)
{ }

but compiler warns me :

CS8625 Cannot convert null literal to non-nullable reference type

List<T> should be nullable by definition, right?


Solution

  • Recently, Microsoft enabled nullable reference types by default on new projects.

    You have five ways to make this warning go away:

    1. You can respect nullable reference types, and change the type of your parameter:
    public static void test(List<String>? list = null) { }
    
    1. You can ignore the null assignment using the ! operator. (I like to call this the "I know better" operator because I will typically use it when I know what I'm assigning is not null but the compiler thinks it could be.)
    public static void test(List<String> list = null!) { }
    
    1. You can disable nullable reference types for just this piece of the code:
    #nullable disable
    public static void test(List<String> list = null) { }
    #nullable restore
    
    1. You can disable nullable reference types for the whole file by putting #nullable disable at the beginning of it (with your namespace declaration)
    2. You can disable nullable reference types for the project. Right click on the project in Solution Explorer -> Properties -> Build -> General -> Nullable.