I'm looking for a way to write code that tests whether a value is boxed.
My preliminary investigations indicate that .NET goes out of its way to conceal the fact, meaning that GetType()
and IsValueType
don't reveal the difference between a boxed value and an unboxed value. For example, in the following LinqPad C# expressions, I have faith that o1
is boxed and i1
is not boxed, but I would like a way to test it in code, or, second best, a way to know FOR SURE when looking at any variable or value, even if its type is "dynamic" or "object," whether it's boxed or not boxed.
Any advice?
// boxed? -- no way to tell from these answers!
object o1 = 123;
o1.GetType().Dump("o1.GetType()");
o1.GetType().IsValueType.Dump("o1.GetType().IsValueType");
// not boxed? -- no way to tell from these answers!
int i1 = 123;
i1.GetType().Dump("i1.GetType()");
i1.GetType().IsValueType.Dump("i1.GetType().IsValueType");
if(oThing.isBoxed) {//do this;} else {//do that;}
?? – UltramundaneAssert()
if the value being passed in by a caller is boxed. The use case is a high-performance library, such that performance degrades if boxed values are used. – Papyrology