What is the behind-the-scenes difference between int?
and int
data types?
Is int?
somehow a reference type?

- 4,136
- 5
- 22
- 41

- 6,640
- 10
- 36
- 41
4 Answers
In addition to "int?" being a shortcut for "Nullable", there was also infrastructure put into the CLR in order to implicitly and silently convert between "int?" and "int". This also means that any boxing operation will implicitly box the actual value (i.e., it's impossible to box Nullable as Nullable, it always results in either the boxed value of T or a null object).
I ran into many of these issues when trying to create Nullable when you don't know T at compile time (you only know it at runtime). http://bradwilson.typepad.com/blog/2008/07/creating-nullab.html

- 67,914
- 9
- 74
- 83
For one of the better "behind the scenes" discussions about Nullable types you should look at CLR Via C# by Jeffrey Richter.
The whole of Chapter 18 is devoted to discussing in detail Nullable types. This book is also excellent for many other areas of the .NET CLR internals.

- 28,450
- 9
- 65
- 75

- 60,973
- 31
- 151
- 169
I learned that you must explicitly cast a nullable value type to a none-nullable value type, as the following example shows:
int? n = null;
//int m1 = n; // Doesn't compile
int n2 = (int)n; // Compiles, but throws an exception if n is null

- 5
- 1
-
No, you shouldnt unless you are totally sure it has the value assigned. The Nullable struct has a property named `HasValue` and a second property with the actual value. This would avoid potential errors `if (n.HasValue) n2 = n.Value;` – Cleptus Aug 10 '20 at 08:26