Carl’s Geek Notes

September 21, 2007

C# string rears its ugly C++ head…

Filed under: C#/.NET, Computers, Microsoft Access, Programming — Carl @ 8:25 am

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.)

Theme: Silver is the New Black. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.