4

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?)
}
4
  • 2
    Quick ways of testing this sort of thing (much quicker than asking SO, in any case) are LINQPad and sharplab.io . As a guideline, if it compiles to the same IL there is no difference. If it compiles to different IL, there could still be no difference if it gets JIT-compiled to the same assembly. Commented Dec 19, 2022 at 16:09
  • @Jodrell: because that only works for your edited version of the question, which changes the semantics of the original, which is why I've rolled it back. In an anonymous object declaration you can't specify the type of the member explicitly, it must be derived from the expression. Commented Dec 19, 2022 at 16:50
  • @JeroenMostert, you have a point, my bad. Although it may be moot. dotnetfiddle.net/JPohDD and sharplab.io/… Commented Dec 19, 2022 at 17:03
  • @Jodrell: not entirely, in this context -- while (bool?) null and default(bool?) work from C# 2 onwards, (bool?) default needs C# 7.1. Not likely to be an issue in practice, of course. Commented Dec 19, 2022 at 17:18

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.