Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use new string in the debugger?

The following code compiles successfully:

string foo = new string(new char[] { 'b', 'a', 'r' });

The following code fails to be evaluated if pasted into the watch window or the Immediate Window:

new string(new char[] { 'b', 'a', 'r' });

The error message is:

'new string(new char[] { 'b', 'a', 'r' })' 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

Why does this happen?

like image 852
Brian Avatar asked Dec 10 '10 22:12

Brian


1 Answers

The C# expression evaluator uses ICorDebugEval & ICorDebugEval2 interfaces to interact with the CLR during a debugging session. That interface does not allow the calling of any constructor on the string type. Instead it forces all calls to create a new instance of string to go through the ICorDebugEval::NewString method. The C# EE does not special case string in the EE hence it tries to call the constructor directly and fails.

Note you won't see this exception with VB.Net in Visual Studio 2010. It will special case calls to the string constructors by evaluating the arguments and forwarding the resulting string object onto ICorDebugEval::NewString

like image 122
JaredPar Avatar answered Sep 24 '22 03:09

JaredPar