views:

69

answers:

2

MSDN docs say that only value types need boxing, but this does not apply to string, which is a value type and does not need to be boxed. I initially tried Type.IsValueType, but since that returns true for string, I can't use it to determine whether a type really needs to be boxed. Are there any other methods you are aware of? Is string the only exception?

UPDATE: I made a mistake in my code where I referenced an int and I thought it was a string. String is in fact a value type, thanks for pointing it out guys!

A: 

Are you writing raw IL? That's the only case in which you'll have to concern yourself with boxing.

Never done any performance critical code?
Stephan Eggermont
Yes, I am in fact writing raw IL, that's why I was asking.
Hermann
Don't forget Hermann, that ints are i4 intrinsics and can often be operated on as intrinsics, without the boxing.
+8  A: 

Your premise is incorrect. String is actually a reference type which just happens to act like a value type in many scenarios. Type.IsValueType is the most reliable way of determining if a value would need to be boxed or not.

I'd be careful if you work with nullable values though.

JaredPar
Yeah, you're right. I just noticed I had a bug in my code where I referenced an int while I thought it was a string.
Hermann