>I've encountered a problem when using the String class in C#. Strings seem
>to be truncated at the first NUL character. Am I correct?

Signature
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
Please reply only to the newsgroup.
> No, .NET strings are generally not null terminated. They have a length
> prefix and can therefore contain any character. But if you display a
> string in a message box or in the debugger, it might be truncated at
> the first null character.
Not only is the display truncated but the length displayed is incorrect:
static void Main(string[] args)
{
char[] chars = {'\0', 'a', '\0', 'c', '\0'};
string s = new String(chars);
System.Console.WriteLine(s.Length);
byte[] bytes = {0, 97, 0, 99};
string t = System.Text.Encoding.ASCII.GetString((byte[]) bytes.Clone());
System.Console.WriteLine(t.Length);
}
If I place a breakpoint on the byte[] bytes = {0, 97, 0, 99} line, the
debugger will report s as being "" and s.Length as 0. But 5 has been written
to the console! Anybody understand this phenominon?
Cheers,
Brian
David Browne - 25 Sep 2003 21:42 GMT
> > No, .NET strings are generally not null terminated. They have a length
> > prefix and can therefore contain any character. But if you display a
[quoted text clipped - 16 lines]
> debugger will report s as being "" and s.Length as 0. But 5 has been written
> to the console! Anybody understand this phenominon?
Bugs in VS 2002, and/or framework 1.0.
In VS 2003 the debugger shows them as
> ? s.Length
5
> ? s
"\0a\0c\0"
>? t.Length
4
> ? t
"\0a\0c"
David
Jon Skeet - 25 Sep 2003 23:34 GMT
> > No, .NET strings are generally not null terminated. They have a length
> > prefix and can therefore contain any character. But if you display a
[quoted text clipped - 16 lines]
> debugger will report s as being "" and s.Length as 0. But 5 has been written
> to the console! Anybody understand this phenominon?
Yup - the debugger thinks it knows best, so doesn't actually invoke the
real String.Length property.
Are you using VS.NET 2002 or 2003? I thought this had been fixed for
2003...

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Brian Quinlan - 27 Sep 2003 00:24 GMT
> Yup - the debugger thinks it knows best, so doesn't actually invoke the
> real String.Length property.
Cute.
> Are you using VS.NET 2002 or 2003? I thought this had been fixed for
> 2003...
I'm still using 2002. I've been eagerly waiting for 2003 to arrive in the
mail for about two months now.
Cheers,
Brian