简体   繁体   中英

In C#, can null be used as a value or operand?

The following C# code:

int? a = null;
Console.WriteLine(a ?? 3);

can print out 3 . But if it is changed to:

Console.WriteLine(null ?? 3);

then it cannot run, giving out

error CS0019: Operator '??' cannot be applied to operands of type '<null>' and 'int' 

Is it possible to use null as a value or operand in C#?

This will work

Console.WriteLine((int?)null ?? 3);

As null doesn't have a type, you need to cast it to the reference type or nullable type

It depends on whether the type is given by the context. For example you can do:

(int?)null ?? 3

or

null ?? (int?)3

If you want boxing instead of wrapping to Nullable<> , that is:

(object)null ?? 3

or

null ?? (object)3

or you could use another base class or interface that an int implements, like:

(IFormattable)null ?? 3

or

null ?? (IFormattable)3

A naked null does not have a type in itself, but it is implicitly convertible to a bunch of types that allow a null value.

For a reference type, the type can be inferred from the context:

null ?? "three"  /* OK */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM