0

Inserting a string into a string doesn't appear to have any effect. I'm using the following code:

string stNum = string.Format("{0:00}", iValue);
DesiredCode.Insert(0, stNum);
txtCode.Text = DesiredCode;

Breakpoints show stNum has the desired value, and DesiredCode is also as we would expect before insertion. But after insertion, nothing will happen and the DesiredCode is the same as before!

Can someone please point me in the right direction as to what I'm doing wrong?

aevitas
  • 3,753
  • 2
  • 28
  • 39
LastBye
  • 1,143
  • 4
  • 19
  • 37
  • Thanks everyone, there was a silly mistake and I thought it is similar to some static extensions but I should return it back to itself. – LastBye Jul 27 '13 at 17:52
  • I've put some +1s to people answering and got some -1s :D, anyway all the answers seems correct and the same, I got the answer instantly, Jon was more explanatory. – LastBye Jul 27 '13 at 17:56
  • 1
    It's probably because of how you wrote your question; I had to read some parts twice before I understood what you were trying to say. – aevitas Jul 27 '13 at 18:14
  • I agree with you, I was shocked for getting a strange result as it seemed to me, and also I think I had some grammatical errors in my text. thanks for reforming it. – LastBye Jul 27 '13 at 18:26

3 Answers3

7

Strings are immutable. All the methods like Replace and Insert return a new string which is the result of the operation, rather than changing the data in the existing string. So you probably want:

txtCode.Text = DesiredCode.Insert(0, stNum);

Or for the whole block, using direct ToString formatting instead of using string.Format:

txtCode.Text = DesiredCode.Insert(0, iValue.ToString("00"));

Or even clearer, in my opinion, would be to use string concatenation:

txtCode.Text = iValue.ToString("00") + DesiredCode;

Note that none of these will change the value of DesiredCode. If you want to do that, you'd need to assign back to it, e.g.

DesiredCode = iValue.ToString("00") + DesiredCode;
txtCode.Text = DesiredCode;
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

Strings are immutable!

DesiredCode = DesiredCode.Insert(0, stNum);
sll
  • 61,540
  • 22
  • 104
  • 156
2

Strings are immutable in C#. What this means is that you need to assign the return value of String.Insert to a string variable after the operation in order to access it.

string stNum = string.Format("{0:00}", iValue);
DesiredCode = DesiredCode.Insert(0, stNum);
txtCode.Text = DesiredCode;
Community
  • 1
  • 1
Adam Maras
  • 26,269
  • 6
  • 65
  • 91