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:
- You can respect nullable reference types, and change the type of your parameter:
public static void test(List<String>? list = null) { }
- 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!) { }
- 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
- You can disable nullable reference types for the whole file by putting
#nullable disableat the beginning of it (with your namespace declaration) - You can disable nullable reference types for the project. Right click on the project in Solution Explorer -> Properties -> Build -> General -> Nullable.