views:

74

answers:

5

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.
+5  A: 

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.

SLaks
+3  A: 

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

Console.WriteLine(x.CompareTo(String.Empty)==0);
Kevin
+7  A: 

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

you could do:

Console.WriteLine(string.IsNullOrEmpty(x));
decasteljau
+3  A: 

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.

Jon Skeet
While this is an interesting point, it's got nothing to do with the question.
SLaks
@Slaks: I don't see how it has nothing to do with the question. In particular, it's a reference to a string, so it's non-null. I think the fact that you get the same reference every time is *entirely* relevant to the question.
Jon Skeet
Is this equivalent to saying two strings instantiated as above will have the same address?
Sorin Comanescu
@Sorin: Yes, it is.
SLaks
@Skeet: I meant that it doesn't help answer the question.
SLaks
@SLaks: In what way? The question is "what value will be assigned to x" and the answer is "a reference to a string - the same (non-null) reference every time you execute the line". How does that not answer the question?
Jon Skeet
A: 

Try this instead:

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