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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
string.Emptyand""both end up as references to a “real” string object which happens to be empty. So you can call methods on it, use itsLengthproperty etc.The
nullreference is a value which doesn’t refer to any object. If you try to dereference null, you’ll get aNullReferenceException.As to whether you choose
""orstring.Empty– that’s really a matter of personal preference. I tend to choose"", but others findstring.Emptymore readable. Note that while""is a constant expression,string.Emptyisn’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.
nullis a value just like any other – it’s just that it doesn’t refer to any object. In particular, assigningnullto 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