Search code examples
c#stringvalue-typeboxingreference-type

Do strings get boxed in C#?


Update Jan 5, 2024: the answer at this link appears to show that the C# compiler completely removes the object cast when trying to cast a string to an object: https://stackoverflow.com/a/51381643/3163495

So, the answer is definitely no, strings do not get boxed.


Original Question:

I understand that value types like int or bool in C# get boxed, like in this example:

int i = 5;
object o = i; // boxing occurs

But do I need to worry about C# boxing string types as well?

string e = "hello world";
object o = e; // does boxing occur here?

I ask because string types are reference types with value semantics, so I'm unsure.


Solution

  • String is a reference type (Strings and string literals doc, Built-in reference types: string doc), boxing applies only to value types - docs:

    Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type.

    so no, they are not boxed when they are cast to object, it is so called implicit reference conversions:

    In other words, while a reference conversion can change the type of the reference, it never changes the type or value of the object being referred to.

    So basically string's are not boxed (or always boxed as soon as you create them - as correctly mentioned by @Charlieface in the comments).