What's the difference between null string and string.Empty?

What's the difference between null string and string.Empty?


Let's continue our 'Back to Basics' series. It's often an interview question to get an idea of the basic knowledge of a candidate. This is one of the simple question that an interviewer may ask during an interview and you should also know this while writing your code.

 

In this post, we are again going to discuss on the basics and this time we will learn the difference between null string and empty string.

 

What's the difference between null string and string.Empty? (www.kunal-chowdhury.com)

 

 

When you set the value of a string variable to 'null', it defines itself as non-initialized variable. As a result, you can't call any of its methods or properties as calling anything on top of a null value will always throw 'NullReferenceException' and you must be already familiar to that.

 

string nullString = null;

 

On the other hand, an empty string contains zero characters in a valid instance of the System.String class. You can create an empty string either by assigning a text value having no character in it (for example, "") or by directly setting 'string.Empty' as its value.

 

string emptyString1 = "";
string emptyString2 = string.Empty;
 

 

The value of 'string.Empty' field, defined under 'System' namespace, is the zero-length string i.e. "". In code, use this field whenever you want to assign or initialize a string variable to an empty string. In a very rare case, you may need to initialize a string variable as 'null'.

 

Was the post helpful? Do let us know below in the comments section. Until the next post, checkout the other posts that I already published. Have a great day!

 

 



If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Twitter, Facebook, Google+ and LinkedIn. I would love to hear your thoughts and opinions on my articles directly. Also, don't forget to share your views and/or feedback in the comment section below.

0 comments

 
© 2008-2017 Kunal-Chowdhury.com - Microsoft Technology Blog for developers and consumers | Designed by Kunal Chowdhury
Back to top