Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I remember this behavior was kind of last minute change. In early betas of .NET 2.0, <code>Nullable&lt;T&gt;</code> was a "normal" value type. Boxing a <code>null</code> valued <code>int?</code> turned it into a boxed <code>int?</code> with a boolean flag. I think the reason they decided to choose the current approach is consistency. Say:</p> <pre><code>int? test = null; object obj = test; if (test != null) Console.WriteLine("test is not null"); if (obj != null) Console.WriteLine("obj is not null"); </code></pre> <p>In the former approach (box <code>null</code> -> boxed <code>Nullable&lt;T&gt;</code>), you wouldn't get "test is not null" but you'd get "object is not null" which is weird. </p> <p>Additionally, if they had boxed a nullable value to a <code>boxed-Nullable&lt;T&gt;</code>:</p> <pre><code>int? val = 42; object obj = val; if (obj != null) { // Our object is not null, so intuitively it's an `int` value: int x = (int)obj; // ...but this would have failed. } </code></pre> <p>Beside that, I believe the current behavior makes perfect sense for scenarios like nullable database values (think SQL-CLR...)</p> <hr> <h3>Clarification:</h3> <p>The whole point of providing nullable types is to make it easy to deal with variables that have no meaningful value. They didn't want to provide two distinct, unrelated types. An <code>int?</code> should behaved more or less like a simple <code>int</code>. That's why C# provides lifted operators. </p> <blockquote> <p>So, when unboxing a value type into a nullable version, the CLR must allocate a <code>Nullable&lt;T&gt;</code> object, initialize the hasValue field to true, and set the value field to the same value that is in the boxed value type. This impacts your application performance (memory allocation during unboxing).</p> </blockquote> <p>This is not true. The CLR would have to allocates memory <strong>on stack</strong> to hold the variable whether or not it's nullable. There's not a performance issue to allocate space for an extra boolean variable.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload