Home > Net >  List<T> is non nullable?
List<T> is non nullable?

Time:01-12

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?

CodePudding user response:

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.

CodePudding user response:

Go into your project file and delete the line that says <Nullable>Enable</Nullable> enter image description here

CodePudding user response:

Once Nullable reference types are enabled, List<T> is not nullable by default.

You have to mark it as nullable explicitly, by appending a ? character.

public static void test(List<String>? list = null)
{ }
  •  Tags:  
  • Related