Search code examples
c#nullablevalue-typeboxingnullable-reference-types

Making value type variables nullable by using "?": does it imply boxing?


Given the following assumptions in C#:

  1. boxing and unboxing let me convert any value type variable to an object type, which is a reference type (therefore it's also nullable), like in the example:
int i = 123;
object box = i;
  1. The "?" operator let me convert a not-nullable integer into a nullable variable, like in the example:

int? n = 0;

My Question: for only reference type variables are nullable, can I say that in the second example I'm doing implicit boxing? In other terms, when I use the "?" operator to make nullable an integer, is there boxing operation implied as well (even if it's not explicit)?


Solution

  • int? is suggar for Nullable<T> See documentation. If we look at the signature of this we see:

    public struct Nullable<T> where T : struct
    {
    ...
        public override bool Equals(object other)
        {
          if (!this.hasValue)
            return other == null;
          return other != null && this.value.Equals(other);
        }
    

    Since it is a struct the value will not be boxed.

    If you need to compare values, n.Equals(1) would cause boxing of the argument. I cannot find any documentation about the equality operator ==, but I think it would be fairly safe to assume that it should not cause boxing.