简体   繁体   中英

Cast to bool nullable of null value VS default value of bool nullable

Is there any difference between those two ways to write the same thing?

int? foo = GetValueOrDefault();

var obj = new
{
    //some code...,
    bar = foo.HasValue ? foo > 0 : (bool?)null
}

VS

int? foo = GetValueOrDefault();

var obj = new
{
    //some code...,
    bar = foo.HasValue ? foo > 0 : default(bool?)
}

Yes, it is the same in this case. A Nullable<bool> is a struct and the language specification states:

The default value of a struct is the value produced by setting all fields to their default value (§15.4.5).

Since a Nullable<T> has these two fields:

private bool hasValue; // default: false
internal T value;  // default value of T, with bool=false

So yes, using their default values has the same effect as using (bool?)null , because (bool?) null is also a Nullable<bool> with hasValue=false (same as using new Nullable<bool>() ).

Why you can assign null at all to a Nullable<T> which is a struct, so a value type? Well, that is compiler magic which is not visible in the source .

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