5

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.

asked Jul 28, 2022 at 7:34
2
  • 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/…. Commented Jul 28, 2022 at 7:43
  • 1
    It'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. Commented Jul 28, 2022 at 7:47

1 Answer 1

5

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.

answered Jul 28, 2022 at 7:53

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.