When you try to cast a value from a type to another incompatible type, you get the following error in C#:
CS0039 Cannot convert type A to B via reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
I understand how to potentially fix this, but my question is about the types of conversions themselves. It mentions reference (superclass to subclass or vice versa), boxing and unboxing (value type to object) and null type (e.g. int to int?) conversions, but then what is a wrapping conversion? This one isn't obvious to me, and searching for this term just brings back results about error CS0039, instead of an explanation of the concept.
Wrapping converts a non-nullable value type to its nullable equivalent. Unwrapping is the reverse. For example:
int x = 5;
int? y = x; // Wrapping
int z = (int) y; // Unwrapping
The C# spec doesn't actually call these "wrapping conversions" and "unwrapping conversions" but it does talk about wrapping and unwrapping. From section 4.1.10 of the C# 5 spec, or the online spec (emphasis mine):
An instance for which
HasValue
is false is said to be null. A null instance has an undefined value. Attempting to read theValue
of a null instance causes aSystem.InvalidOperationException
to be thrown. The process of accessing theValue
property of a nullable instance is referred to as unwrapping. In addition to the default constructor, every nullable typeT?
has a public constructor that takes a single argument of typeT
. Given a valuex
of typeT
, a constructor invocation of the formnew T?(x)
creates a non-null instance of
T?
for which theValue
property isx
. The process of creating a non-null instance of a nullable type for a given value is referred to as wrapping.
See more on this question at Stackoverflow