liveBook · Manning

Non-nullable type

As explained in Pro ASP.NET Core 7, Tenth Edition

A non-nullable variable is a variable whose type does not permit the special null value.

A non-nullable variable has a type that cannot receive null. With null state analysis enabled, the compiler warns when code assigns null to such a variable or accesses a nullable value without checking it first. A string is non-nullable; string? permits either a string value or null. section 5.4

Choose the declaration that matches where null is allowed:

  • Use string when the value must exist and callers should be able to use it without a null guard. section 5.4
  • Use string? when null is a valid result; consumers should check before accessing its members. section 5.4
  • Use required for a non-nullable property whose value must be supplied during object creation. section 5.4.1
  • Use a default such as string.Empty when missing input should produce a consistent fallback instead of a build error. section 5.4.2

A Product model with enforced or defaulted names

public required string Name { get; set; }\n\nProduct kayak = new Product { Name = "Kayak" };\n\nOmitting Name from an object initializer produces a build error. If a fallback is preferable, declare the property as public string Name { get; set; } = string.Empty;. section 5.4.1 section 5.4.2

The question mark applies to the element, the container, or both. Product?[] allows null Product elements but requires a non-null array; Product[]? allows only non-null Products but permits a null array; Product?[]? allows both. section 5.4.3

Figure 5.2 A null state analysis warning

Use the warning visualization to identify assignments or member accesses that violate the declared null state. section 5.4

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Explains declarations, required initialization, defaults, and array nullability, including how element and container annotations differ.
Examples
Uses Product.Name, Product arrays, Kayak and Lifejacket objects, null elements, required initializers, and string.Empty defaults.
What you can do after
Apply nullable annotations, required members, and defaults to make C# object and collection null behavior compile-time explicit.
How it connects
Connects null state analysis, nullable types, required members, default values, object initializers, and arrays.

Also explained in

Compare how 2 books explain non-nullable type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.