1

I have function which accepts string (which is basically a XML doc). I am making this change:

  if (filterXml.Contains("&"))
    {
        filterXml.Replace("&", "&");
    }

It is hitting this condition but not replacing the

 & to &

What is wrong here?

RG-3
  • 6,088
  • 19
  • 69
  • 125
  • [Similar questions](http://stackoverflow.com/questions/894905/how-to-replace-occurrences-of-with-an-empty-string) – Cemo Oct 03 '11 at 18:26

5 Answers5

13

Remember, strings are immutable. So you have to assign the return value of the Replace method (notice that it returns a String object) back to your variable.

  if (filterXml.Contains("&"))
  {
      filterXml = filterXml.Replace("&", "&");
  }

If you're doing a lot of work with String objects, make sure to read the the String reference page

Babak Naffas
  • 12,395
  • 3
  • 34
  • 49
7

You need to save the result:

filterXml = filterXml.Replace("&", "&");

but I would recommend encoding ALL special XML characters.

Jared Peless
  • 1,120
  • 9
  • 11
  • Because strings are immutable. They don't change. They can't change. They won't change. Replace and similar methods don't change the string, they return a new, different string with the change applied. – phoog Oct 03 '11 at 18:27
  • @phoog The SHOULDN'T change. Quite different :-) Try looking at the StringBuilder.ToString of C# 2.0 with IlSpy and follow the string.InternalCopy :-) – xanatos Oct 03 '11 at 18:36
6

You don't even need to do the Contains check. Just do the following:

filterXml = filterXml.Replace("&", "&");

If there aren't any ampersands in the string, then nothing will change.

DJ Quimby
  • 3,669
  • 25
  • 35
4

Try -

  if (filterXml.Contains("&"))
    {
        filterXml = filterXml.Replace("&", "&");
    }

Strings are immutable in .net, so the replace function returns a new string rather than altering the string it is called on. You are able to assign the altered result to the variable that contained your original string value.

ipr101
  • 24,096
  • 8
  • 59
  • 61
1
  if (filterXml.Contains("&"))
    {
        filterXml = filterXml.Replace("&", "&");
    }
AndrewC
  • 6,680
  • 13
  • 43
  • 71