On the dangers of unsafe String handling...

Another interesting tidbit I learned today from Brian Grunkemeyer, BCL developer …

It may be tempting to be ultra fast and use C# unsafe code support to just party over memory and write your own string like this:

string s = new string(‘\0’, buffer.Length);

fixed(byte* pBuffer = buffer)

{

            fixed(char* pString = s)

            {

                        for(int i = 0; i < buffer.Length; i++)

                                    pString[i] = (char) pBuffer[i];

            }

}

But you should be aware of the issues with doing something like this…. Here is Brian’s comments (slightly edited):

The reason you should avoid this kind of code is that we have some additional bits stored in a string instance that tell the runtime whether we can do some optimized sorting & comparison, or whether we have to load an NLS data table to get culture-correct weights for each character when comparing them. You may make your string very quickly, but it might not sort right at all. These bits are stored somewhere else in the string instance where you can’t manipulate them. We might add or subtract bits like this in other versions of the Framework as well. (Additionally, some strings may be stored in read-only pages in the future as well.) Using unsafe code to write over a string is not always a good idea…

I would suggest looking at the Rotor source for more info if you really feel you have to go this way…