Reputation: 1173
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?
Upvotes: 0
Views: 103
Reputation: 26843
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;
Upvotes: 2
Reputation: 1499780
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;
Upvotes: 7