Saturday, March 21, 2009

String Construtor String(Char[] value) doesn't work?

So for some reason that I can't determine I'm unable to use the New String(char[] value) function.  I tried this expression in my immediate window while debugging a Windows Mobile 6 .Net 3.5 application, and this is what I got:

?new string(new char[]{'1'})
A first chance exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
'new string(new char[]{'1'})' threw an exception of type 'System.InvalidOperationException'
    base {System.SystemException}: {"InvalidOperationException"}

If I typed the same expression into a normal C# desktop app .Net 3.5 application, this is what I got:

?new string(new char[]{'1'})
'new string(new char[]{'1'})' threw an exception of type 'System.ArgumentException'
    base {System.SystemException}: {"Only NewString function evaluation can create a new string."}
    Message: "Only NewString function evaluation can create a new string."
    ParamName: null

I'm exteremly puzzeled.  Anyone have any ideas?

2 comments:

Edokan said...

Hi,

NewString is the name of the command which is used in CorDbg. Since we are not using CorDbg, getting this exception is very silly.

I currently use a not-so-nice workaround for this.

In "Immediate Window", I create and instance of StringBuilder, append char array, and call ToString of string builder.

StringBuilder sb = new StringBuilder();
sb.Append(new char[] {'1', '2', '3'});
sb.ToString()
System.IO.File.WriteAllText( "c:\\temp\\doNotTryAtHome.txt", sb.ToString())

Daryl said...

So that works. Using Reflector, the Append method converts the char[] to a string using some pointer magic. The String(char[]) constructor actually makes some low level call that won't show up in Reflector. Must be a bug.

It would still be nice to not have to jump through such a hoop though.