Does casting null differ before boxing string?

Present the code like this:

var str = (String)null;

      

Does it differ from:

String str;

      

Or:

String str = null;

      

Is the first code the reason for boxing a null value, or is it rather resolved at compile time for a string?

+3


source to share


4 answers


Let me answer your question and analyze it.

Will the code in your question call boxing?

No, it will not.

It's not because any of the three operators work differently (there are differences, albeit below), but boxing is not a concept that comes up when using strings.

Boxing happens when you take a value type and wrap it in an object. A string

is a reference type and so there will never be boxing with it.

So boxing is gone, but what about the rest, are the three operators equal?



These two will do the same:

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

      

The third (second in the order of your question) differs in that it only declares the identifier as a str

type string

, it does not specifically initialize it before null

.

However , if it is a class field declaration, it will be the same, since all fields are initialized to default values ​​/ zeros when the object is constructed, and therefore will actually be initialized null

anyway.

If, on the other hand, it is a local variable, you now have an uninitialized variable. Judging from what you write var ...

, which is illegal in terms of margins, this is probably more correct for your question.

+8


source


String

is a reference type, so no, no boxing.

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

      

The two are equivalent. On the first line, the compiler displays the type str

on the right side of the expression. In the second line, the cast from null

to is String

implicit.



String str;

      

The latter is equivalent String str = null

if it is a field declaration, which means str

it will be assigned its default value, which is null. If, however, str

is a local variable, it must be explicitly assigned before you can use it.

+9


source


MSDN says,

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

String

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

Yes, they are equal. Since the string is a reference type even though you say string str

; it will get a default value which isnull

+4


source


These two are equal:

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

      

However, this,

String str;

      

Depending on the context, it may or may not be equal to the previous expressions. If it is a local variable, then it is not equal. You must initialize it explicitly. If it is a class variable, then it is initialized to zero.

Nothing triggers boxing.

+3


source







All Articles