The difference between String.Empty, string= "" and null

Source: Internet
Author: User

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

String.Empty and string= "" are not very different, because the internal implementation of String.Empty is:

123456789101112 publicstaticreadonlystringEmpty;//这就是String.Empty 那是只读的String类的成员,也是string的变量的默认值是什么呢?//String的构造函数staticString(){    Empty = "";//Empty就是他""    WhitespaceChars = newchar[] {        ‘\t‘‘\n‘‘\v‘‘\f‘‘\r‘‘ ‘‘\x0085‘‘\x00a0‘‘?‘‘ ‘‘ ‘‘ ‘‘ ‘‘?‘‘?‘‘?‘,        ‘?‘‘?‘‘ ‘‘?‘‘‘‘\u2028‘‘\u2029‘‘ ‘‘‘     };}

  

Look at the code again:

12345678 strings1 = "";string s2 = string.Empty;if(s1 == s2)<br>{    Console.WriteLine("一模一样!");}   // 结果都是TrueConsole.WriteLine("".Equals(string.Empty));Console.WriteLine(object.ReferenceEquals(string.Empty, ""));

Since String.Empty and string= "" also need to occupy memory space, why is it recommended to use String.Empty first?

String. Empty just lets the code read, preventing the code from making ambiguity, such as saying:

string s = "";   string s = ""; It's hard to see whether it's an empty string or a space character.

If a string is judged to be empty, use the

if (S==string.empty) and if (s== "") are the same efficiency, but the most efficient way to do this is if (s.length==0)

String. IsNullOrEmpty's internal implementation method:

publicstatic boolIsNullOrEmpty(stringvalue)<br>{<br>    if(value != null)    {        return(value.Length == 0);    }    returntrue;}

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

The difference between String.Empty, string= "" and null

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.