开发者

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

开发者 https://www.devze.com 2023-01-05 02:06 出处:网络
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

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?


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.


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


That's not the case. Nullable<T> is generic, so it holds the real int or bool.

The MSDN page is talking about what happens when you box a Nullable<int> or Nullable<bool>. If you never assign your nullable struct to an object variable, you won't incur boxing overhead.

0

精彩评论

暂无评论...
验证码 换一张
取 消