user3163495
user3163495

Reputation: 3682

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.

Upvotes: 2

Views: 210

Answers (3)

Guru Stron
Guru Stron

Reputation: 143513

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).

Upvotes: 4

Mark Benningfield
Mark Benningfield

Reputation: 2912

Notwithstanding the "mental laziness" of some sources, strings do not have value semantics. Immutability and value equality are not the primary characteristics of value semantics.

Local values are allocated on the stack, not the heap. All instances of a value are the same size. On assignment, the actual value is copied. Strings do none of these things.

So, to say that they have value semantics is "fudging" the definition by quite a bit, leading to the kinds of uncertainty which your question presents.

Upvotes: -1

user1924249
user1924249

Reputation: 566

That's not boxing at all. String is a reference type, only value types can be boxed. String already lives in heap.

Object o = e is upcasting since object is root for all type

Upvotes: 0

Related Questions