开发者

String Assignment -Clarification

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开发者_JS百科 returns false.


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

you could do:

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


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.


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.


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

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


Try this instead:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜