Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

are C# int? and bool?s always boxed when hasvalue = true?

Tags:

c#

nullable

This MSDN reference seems to indicate that when an int? (or any Nullable<T>) has a value, it's always boxed (and hence a much less efficient store of data, memory-wise than an int). Is that the case?

like image 833
Dan Davies Brackett Avatar asked Jun 30 '10 16:06

Dan Davies Brackett


2 Answers

That page refers to when you are boxing the Nullable<T> struct, not the values inside the struct itself.

There is no boxing involved in storing a nullable type until you try boxing the nullable itself:

int? a = 42; // no boxing
int? n = null; // no boxing

object nObj = n; // no boxing
object aObj = a; // only now will boxing occur

This behavior is no different than when boxing a regular value type (with the exception of handling the null case) so it is really to be expected.

like image 90
Justin Niessner Avatar answered Sep 25 '22 11:09

Justin Niessner


No. The Nullable object is a generic struct, and internally handles the value of T without boxing.

like image 27
BC. Avatar answered Sep 23 '22 11:09

BC.