.NET strings are not always immutable!

Strings are im­mutable. If you want to mod­ify a se­quence of char­ac­ters, use StringBuilder. At least, that’s whats of­fi­cially said. But in the frame­work there is at least one method that does mod­ify a string:

TextRenderer.MeasureText() with ModifyString and EndEllipses will mod­ify your string to match the el­lipsed text if el­lips­ing hap­pens. You can look at this VB# ex­am­ple on code­pro­ject using TextRenderer.MeasureText() for trim­ming text on how it is used.

The string seems to be mod­i­fied di­rectly in na­tive code by DrawTextEx from user32.dll. Ad­di­tion­ally to the scary fact that strings are not im­mutable, the length of the string is not up­dated, re­gard­less if the re­sult­ing string is shorter!

For in­stance if you have a string “aaaaaaa” which will be trun­cated to “aa...“, the Length prop­erty will still re­turn 7 for the short­ened string. The de­bug­ger shows that the string will in fact be “aa…\0a” after the op­er­a­tion. So maybe it might be right that the string is still 7 char­ac­ters long but most out­putting func­tion­al­ity like Console.Out.WriteLine() gets con­fused some­times and stops any fur­ther out­put to the de­bug­ger or con­sole under cer­tain con­di­tions.

A very quick in­ves­ti­ga­tion of the Sys­tem.Draw­ing as­sem­bly using Lutz Roeder’s fab­u­lous .NET Re­flec­tor showed that at least there should be no mem­ory cor­rup­tion in case “WW” would get el­lipsed to “W...“, as DrawTextEx takes the length of the buffer and should re­sult only in “W.“.

Sum­ming up, I find the cor­rup­tion of an im­mutable string by an of­fi­cial Mi­crosoft API very trou­bling.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.