In Microsoft official Learning Module "Create a Web API with ASP.NET Core" Why some sample codes use nullable string type although we know strings are nullable in itself since it is a reference type? See Model/Pizza.cs class in this tutorial.
-
I think it's so that you can effectively flag where something could be null (absence of data) and therefore requires null checks vs something that can't be null. More info: focisolutions.com/2021/04/nullable-reference-types-in-c-8-0/….sr28– sr282022年07月28日 07:43:46 +00:00Commented Jul 28, 2022 at 7:43
-
1It's called "Nullable Reference Type" aka NRT. Relatively new feature of C# helping devs to know when something can be null or it's guarantied no never be null.Artur– Artur2022年07月28日 07:47:35 +00:00Commented Jul 28, 2022 at 7:47
1 Answer 1
In C# 8.0, a new language feature was introduced for nullable reference types which was intended to help remove the whole class of problems around accidentally dereferencing null
objects.
By assuming that all reference types are not actually nullable, the compiler can flag up suspicious code based on its own analysis of how null
values may propagate through the code.
The ?
annotations you see in the tutorial are indications of what fields/properties etc. are allowed to contain null
and therefore need to be checked as such before doing anything with them.