what is the difference among these
1. string str=string.Empty;
2. string str="";
3. string str=null;
and is there any different way to use these statements...
thanks saj
what is the difference among these
1. string str=string.Empty;
2. string str="";
3. string str=null;
and is there any different way to use these statements...
thanks saj
string.Empty
and ""
both end up as references to a "real" string object which happens to be empty. So you can call methods on it, use its Length
property etc.
The null
reference is a value which doesn't refer to any object. If you try to dereference null, you'll get a NullReferenceException
.
As to whether you choose ""
or string.Empty
- that's really a matter of personal preference. I tend to choose ""
, but others find string.Empty
more readable. Note that while ""
is a constant expression, string.Empty
isn't, so you can't use the latter in case statements.
EDIT: Note that both of the other answers present at the time of this edit imply that null is not a value, or that the variable hasn't been assigned a value. This is incorrect. null
is a value just like any other - it's just that it doesn't refer to any object. In particular, assigning null
to a variable will overwrite any previous value, and if it's a local variable that assignment means the variable has been "definitely assigned". For example, compare these two snippets
string s;
Console.WriteLine(s); // Compile-time error: s isn't definitely assigned
string s = null;
Console.WriteLine(s); // Fine: s has the value null
string.Empty
is a different way of saying ""
. (according to Jon Skeet, use whatever is common in your team).
And null means it wasn't assigned a value at all.
(But the Skeet is here to explain that himself (-: )