Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading