I have the following code
char ptr=new char();
int counter = 1;
string s = new System.String(ptr, counter);
// does not show something
MessageBox.Show(s+"Something");
//shows something
MessageBox.Show("Something" + s);
The first Messagebox shows nothing 
The Second Messagebox shows something 
If the counter value is 0 then both messagebox shows same result but if counter is greater than 0 then the problem occurs.
I think the problem is with new string(ptr, counter) initilization
. But I want to know the internal mechnism why this is occured.
ptris a null character ('\0') andsis astringwith one copy of that character (i.e."\0"). So, at runtime, your first call’s parameter evaluates to"\0Something"whereas your other one evaluates to"Something\0".In C#,
strings are allowed to have null characters; you can conceptualize them as just achar[]array (which has a known length); So null characters are OK. The issue comes about when you pass to a C API. C doesn’t have strings, so they’re immitated using null-terminated strings. As far as any C API is concerned,"\0Something"is an empty string (strlenwould return 0). So, when you useMessageBox.Show, your string is passed on down to the Win32 API function,MessageBoxWwhich only understands null-terminated strings.From the .NET source code for
MessageBox.Show(string)Towards the end of
ShowCore, we see this line:And that
MessageBoxWcall is that Win32 API function inuser32.dll.