Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why '\0'.ToString()==string.Empty returns FALSE?

Tags:

string

c#

.net

I just cannot get the point: If '\0' is an empty char and if a string is a kind of array of chars why this happens?

char value = '\0';
bool isEmpty = value.ToString() == string.Empty; // This returns FALSE because 
                                                 // '\0'.ToString() returns "\0" 
                                                 // where I expect it to be 
                                                 // string.empty
like image 481
pencilCake Avatar asked Oct 26 '11 15:10

pencilCake


1 Answers

There's no such thing as an "empty char", so your assumption in the first sentence is incorrect. A string with a single character (U+0000) is not the same as an empty string - for a start, the length of the first string is 1, not 0.

Calling ToString() on a char will always return a string of length 1, containing just that character. That's the only thing that it makes sense to do, IMO. I don't know why you would expect anything else.

While U+0000 is often used as a terminating character, it's not the same as the character "not existing". The string "Foo\0Bar" is not the same as "FooBar", and shouldn't be treated the same.

In short: it's your expectations which are incorrect, not .NET :)

like image 78
Jon Skeet Avatar answered Oct 01 '22 13:10

Jon Skeet