Monday, June 23, 2008

myString.Replace("Blah", "Blah Blah") - DONT TRY THIS AT HOME! Strings are immutable!

I hope I can save someone some time from this little mind boggler....

I had a string, I wanted to change one particular part of the string... NO PROBLEM -- use .Replace right? well, sort of.

Strings are immutable objects and cannot be changed -- so saying

msgText.Replace ("5 of 6", "3 of 5")

may look good and will not even give you an error (unfortunately) BUT it also WILL NOT WORK!

You have two options... create a different string to house the Replaced string OR create a stringBuilder.

I chose to use a new string and the .Replace worked great.

myNewText = msgText.Replace ("5 of 6", "3 of 5")

all is well again.

No comments: