Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.Replace not behaving as expected

Tags:

string

c#

.net

Can someone explain why I get different results from these two statements? I thought that reassigning the value to the same variable would result in the value I get in the above example. What am I missing here?

_body.Replace("##" + _variableName + "##",
    templateVariables[_variableName])

Hello pitty ##LastName##,

_body = _body.Replace("##" + _variableName.ToUpper() + "##", 
    templateVariables[_variableName])

Hello ##FirstName## ##LastName##,


2 Answers

Strings are immutable, so the Replace function doesn't modify the string it is called on. You need to assign it again like you did in your second example.

And as other people have pointed out, the ToUpper call will ensure that variable names don't match.

like image 182
Ray Avatar answered Apr 24 '26 07:04

Ray


If I understand this correctly: Your first statement is not assigning the return value, since replace returns a new instance of the string replaced.

_body = _body.Replace("##" + _variableName + "##",
    templateVariables[_variableName]);

should fix you there.

The second instance you have the variable getting replace changed ToUpper() and the actual string containing mixed cased values.

Your string should be

Hello ##FIRSTNAME## ##LASTNAME##, 
like image 32
Pat Avatar answered Apr 24 '26 06:04

Pat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!