Difference between string. Empty, string = "" and null

Source: Internet
Author: User

String. Empty is a static constant of the string class;

The difference between string. Empty and string = "is not big, because the internal implementation of string. Empty is:

Public static readonly string empty; // This is string. Empty. It is a read-only member of the string class. What is the default value of the string variable? // String's constructor static string () {empty = ""; // empty is his "" whitespacechars = new char [] {'\ t',' \ n ', '\ V',' \ F', '\ R', '',' \ x0085 ',' \ x00a0 ', 'hangzhou ','','','', 'taobao ','','','','', '\ u2028',' \ u2029 ','',''};}

  

Let's look at another piece of code:

String S1 = ""; string S2 = string. Empty; If (S1 = S2)
{Console. writeline ("Exactly! ");} // The result is trueconsole. writeline (" ". Equals (string. Empty); console. writeline (object. referenceequals (string. Empty ,""));

Since string. Empty is the same as string = "" and it also needs to occupy memory space, why is string. Empty recommended?

String. Empty only allows the code to be read well and prevents code ambiguity. For example:

String S = ""; string S = ""; this is not very careful, it is difficult to see whether it is a null string or a space character.

 

If you determine whether a string is a Null String, use

If (S = string. Empty) And if (S = ") have the same efficiency, but the most efficient way is if (S. Length = 0)

String. isnullorempty internal implementation:

public static bool IsNullOrEmpty(string value)
{
if (value != null) { return (value.Length == 0); } return true;}

String STR = NULL indicates that STR does not point to any object.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.