Nullable Types (?) (C#)

  • 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>
ValueRemarks
enableNullable annotations enabled, nullable warnings enabled.
warningsNullable annotations disabled, nullable warnings enabled.
annotationsNullable annotations enabled, nullable warnings disabled.
disableNullable 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 directiveRemarks
enableAnnotations enabled, warnings enabled
disableAnnotations disabled, warnings enabled
restoreRestore all settings to project settings
disable warningsonly disable warnings
enable warningsonly enable warnings
restore warningsonly restore warnings
disable annotationsonly disable annotations
enable annotationsonly enable annotations
restroe annotationsonly restore annotations

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值