Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a wrapping conversion?

Tags:

c#

casting

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.

like image 355
Arturo Torres Sánchez Avatar asked Feb 27 '18 16:02

Arturo Torres Sánchez


2 Answers

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 the Value of a null instance causes a System.InvalidOperationException to be thrown. The process of accessing the Value property of a nullable instance is referred to as unwrapping. In addition to the default constructor, every nullable type T? has a public constructor that takes a single argument of type T. Given a value x of type T, a constructor invocation of the form

new T?(x)

creates a non-null instance of T? for which the Value property is x. The process of creating a non-null instance of a nullable type for a given value is referred to as wrapping.

like image 154
Jon Skeet Avatar answered Oct 14 '22 15:10

Jon Skeet


As stated in the spec:

If the nullable conversion is from S to T?, the conversion is evaluated as the underlying conversion from S to T followed by a wrapping from T to T?.

Which implicitly means that wrapping means to turn a non-nullable into it's nullable type variant.

like image 20
Hatted Rooster Avatar answered Oct 14 '22 16:10

Hatted Rooster