Search code examples
c#castingdefaultnullableanonymous-class

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?)
}

Solution

  • It is the same. 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 default(bool?) 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.