Follow us on X (Twitter)  Like us on Facebook  Connect with us on LinkedIn  Subscribe to our YouTube Channel  Subscribe to our WhatsApp Group

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!

 

 

Have a question? Or, a comment? Let's Discuss it below...

Thank you for visiting our website!

We value your engagement and would love to hear your thoughts. Don't forget to leave a comment below to share your feedback, opinions, or questions.

We believe in fostering an interactive and inclusive community, and your comments play a crucial role in creating that environment.