string is a reference type;
string str = null does not create memory space, and str stores a null reference pointer;
string str = "" Creates a memory space, and str stores a pointer to the heap.
general speaking:
string str ="";
give you a blank sheet of paper;
string str = null;
Not even white paper.
string.Empty is equivalent to ""
Generally used for string initialization
for example:
string a;
Console.WriteLine(a);// An error will be reported here because a is not initialized
And the following will not give an error:
string a=string.Empty;
Console.WriteLine(a);
or for comparison:
if(a=="")
if(a==string.Empty)
The above two sentences have the same effect.
string.Empty does not allocate storage
"" Allocate an empty storage space
So generally use string.Empty
For future cross-platform, use string.empty
在 C# 中,大多数情况下 "" 和 string.Empty 可以互换使用。比如:
string s = "";
string s2 = string.Empty;
if (s == string.Empty) {
//
}
if语句成立
判定为空字符串的几种写法,按照性能从高到低的顺序是:
s.Length == 0 优于 s == string.Empty 优于 s == ""
您关于String.Empty和Null的问题是这样的,这两个都是表示空字符串,其中有一个重点是string str1= String.Empty和 string str2=null 的区别,这样定义后,str1是一个空字符串,空字符串是一个特殊的字符串,只不过这个字符串的值为空,在内存中是有准确的指向的,string str2=null,这样定义后,只是定义了一个string 类的引用,str2并没有指向任何地方,在使用前如果不实例化的话,都将报错。textBox1.Text的值为零长度字符串 ""。
问题来自于对控件的Text属性理解错误。
一:null和空的区别
1.声明的string类型的变量和属性以及字段在未赋值的情况下均为null,这个null不仅仅表示为无字符,更表示为空的引用。
比如:string userName;此时判断userName是否为空应该是if(userName==null)而不是if(userName==“”),并且使用userName.Equals(null)或userName.Equals(“”)均为错的,因为此时userName是个空引用,根本无法调用Equals()方法。但是如果声明为string userName=“”,则上述方法均成立。但是此时userName并不是null而是空值。
2.所有控件的Text属性的在未赋值的情况下是空值(""), 而不是null。