-
Nullable Value Type
The ? suffix is a shorthand for creating an instance of the generic System.Nullable<T> structure.
static void NullableItems()
{
int? item1 = 0;
// Nullable<int> item1 = 0;
bool? item2 = null;
// Nullable<bool> item2 = null;
char?[] arrChar=new char?[5];
// Nullable<int>[] arrChar = new Nullable<char> [5]
}
nullableVariable.HasValue
NullableItems();
static void NullableItems()
{
int? item1 = 0;
// Nullable<int> item1 = 0;
bool? item2 = null;
// Nullable<bool> item2 = null;
char?[] arrChar=new char?[5];
// Nullable<int>[] arrChar = new Nullable<char> [5]
string result1 = (item1 != null) ? ($"The value of item1 is {item1}") :
("The value of item1 has not been defined.");
Console.WriteLine(result1);
string result2 = (item2.HasValue) ? ($"The value of item2 is {item2}") :
("The value of item2 has not been defined.");
Console.WriteLine(result2);
Console.ReadLine();
}
-
Nullable Reference Type (C# 8.0)
To enable nullable reference type, modify the value in project file as follows:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
Value | Remarks |
---|---|
enable | Nullable annotations enabled, nullable warnings enabled. |
warnings | Nullable annotations disabled, nullable warnings enabled. |
annotations | Nullable annotations enabled, nullable warnings disabled. |
disable | Nullable annotations disabled, nullable warnings disabled. |
Use compiler directives to enable or disable nullable contexts
using ConsoleApp11;
Person? p = null;
string? nullString = null;
#nullable disable
// Warning: The annotation for nullable reference types
// should only be used in code within a '#nullable' annotations
Person? person1 = null;
#nullable restore
Value of nullable compiler directive | Remarks |
---|---|
enable | Annotations enabled, warnings enabled |
disable | Annotations disabled, warnings enabled |
restore | Restore all settings to project settings |
disable warnings | only disable warnings |
enable warnings | only enable warnings |
restore warnings | only restore warnings |
disable annotations | only disable annotations |
enable annotations | only enable annotations |
restroe annotations | only restore annotations |