Does casting null differ before boxing string?
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.
source to share
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.
source to share
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
source to share
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.
source to share