Gumowy Kaczak
Gumowy Kaczak

Reputation: 1499

Does casting null to string cause boxing?

Imagine code like this:

var str = (String)null;

Does it differs from:

String str;

Or:

String str = null;

Does the first code cause boxing of null value, or is it rather resolved at compiler time to string?

Upvotes: 3

Views: 266

Answers (4)

dcastro
dcastro

Reputation: 68670

String is a reference type, so no, there's no boxing.

var str = (String)null;
String str = null;

These two are equivalent. In the first line, the compiler infers the type of str from the right hand side of the expression. In the second line, the cast from null to string is implicit.

String str;

The last one is equivalent to String str = null if it's a field declaration, which means str will be assigned its default value, which is null. If, however, str is a local variable, it'll have to be explicitly assigned before you can use it.

Upvotes: 9

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391396

Let's take your question and pick it apart.

Will the code in your question cause boxing?

No, it will not.

This is not because any of the 3 statements operate differently (there are differences though, more below), but boxing is not a concept that occurs when using strings.

Boxing occurs when you take a value type and wrap it up into an object. A string is a reference type, and thus there will never be boxing involved with it.

So boxing is out, what about the rest, are the three statements equal?

These two will do the same:

var str = (String)null;
String str = null;

The third one (second one in the order of your question though) is different in the sense that it only declares the str identifier to be of type String, it does not specifically initialize it to null.

However, if this is a field declaration of a class, this will be the same since all fields are initialized to defaults / zeroes when an object is constructed, and thus it will actually be initialized to null anyway.

If, on the other hand, this is a local variable, you now have an uninitialized variable. Judging from the fact that you write var ..., which is illegal in terms of fields, this is probably more correct for your question.

Upvotes: 8

Rahul
Rahul

Reputation: 77876

MSDN says,

Boxing is the process of converting a value type to the type object

String is not a value type and so there will be no boxing/unboxing.

Yes they are equal. Since string is a reference type even if you say string str; it will get default value which is null

Upvotes: 4

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181290

These two are equal:

var str = (String)null;
String str = null;

However, this one,

String str;

Depending on the context might or might not be equal to previous expressions. If it's a local variable, then it's not equal. You must explicitly initialise it. If it's a class variable, then it's initialised to null.

Neither cause boxing.

Upvotes: 3

Related Questions