C# string rears its ugly C++ head…

Here’s one that I won’t forget soon.  I was working on an application that reads data from a Microsoft Access database and builds a string:

string MyString = MyTable.Rows[i]["MyColumn"].ToString();
string NewString = "stuff " + MyString + " some other stuff";

Pretty basic stuff.  I was seeing a problem where NewString’s value was (assuming MyString = “MyStringData”) “stuff MyStringData”–it cut off everything in the string after MyString.

The issue?  When MyString is assigned, it includes \0 at the end (the string terminator character from C).  .NET apparently stops marshalling at that point.  I corrected it by:

string MyString = MyTable.Rows[i]["MyColumn"].ToString().Replace("", "");

I don’t know whether Access returned it terminated, or the application that originally wrote the data added the string terminator (which I suspect, as I’ve written tomes of code that pull data from Access in my life).  I finally found it by breaking into the application, and when I hovered the cursor over MyString its data was displayed as “MyStringData\0”.  (FYI, it appeared as just “MyStringData” in the string visualizer and Watch window, it was only the hover-over that gave it away.)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s