String Assignment -Clarification

为君一笑 提交于 2019-12-12 01:18:25

问题


When i declare

string x = new string(new char[0]);

It works fine.My question is what value will be assigned to x ?

when i check

Console.WriteLine(x.CompareTo(null)==0);,it returns false.

回答1:


when you assign new char[0], your string is not null. It is empty.

you could do:

Console.WriteLine(string.IsNullOrEmpty(x));



回答2:


x will be an empty string, the same as x = "".

null and "" are two distinct string values. In particular, null is a null reference, so you cannot call any instance members on it. Therefore, if x is null, x.Length will throw a NullReferenceException.

By contrast, "" (or String.Empty) is an ordinary string that happens to contain 0 characters. Its instance members will work fine, and "".Length is equal to 0.

To check whether a string is null or empty, call (surprise) String.IsNullOrEmpty.




回答3:


You've picked an interesting case here, because on .NET it violates the principle of least surprise. Every time you execute

string x = new string(new char[0]);

you will get a reference to the same string.

(EDIT: Just to be very clear about this - it's a non-null reference. It refers to a string just as it would if you used any other form of the constructor, or used a string literal.)

I'm sure it used to refer to a different string to "", but now it appears to be the same one:

using System;

public class Test
{
    static void Main()
    {
        object x = new string(new char[0]);
        object y = new string(new char[0]);
        object z = "";
        Console.WriteLine(x == y); // True
        Console.WriteLine(x == z); // True
    }
}

As far as I'm aware, this is the only case where calling new for a class can return a reference to an existing object.




回答4:


The string is isn't null, it's empty.

Console.WriteLine(x.CompareTo(String.Empty)==0);



回答5:


Try this instead:

Console.WriteLine(x.CompareTo(string.Empty) == 0);


来源:https://stackoverflow.com/questions/1643235/string-assignment-clarification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!