user65199
user65199

Reputation:

How to determine if type needs to be boxed?

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!

Upvotes: 2

Views: 156

Answers (2)

JaredPar
JaredPar

Reputation: 755041

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.

Upvotes: 8

user168785
user168785

Reputation: 21

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

Upvotes: 1

Related Questions