1

Does this code takes x and changes its contents directly or creates a temporary new string then copy to x?

If the latter is true, I don't understand why we use ref.

public static void RemoveSpaces(ref string x)
    {
        x = x.Replace(" ", "");
    }
Lyrk
  • 1,936
  • 4
  • 26
  • 48
  • 3
    Considering that strings in c# are immutable, yes, a new instance is created and then the pointer of `x` is assigned to that new instance. – zaitsman Dec 27 '17 at 12:35
  • Possible duplicate of [What is the difference between a mutable and immutable string in C#?](https://stackoverflow.com/questions/4274193/what-is-the-difference-between-a-mutable-and-immutable-string-in-c) – Progman Dec 27 '17 at 12:35
  • @zaitsman pointer of the new instance is assigned to x or opposite? I mean does x holds the address of the first character of newly formed string? – Lyrk Dec 27 '17 at 12:39
  • 3
    Key point to understand is that `x` is not a string but a reference to a string object. And without `ref` that reference would be passed by-value and the effects would not be visble after the method. – H H Dec 27 '17 at 12:40

3 Answers3

5

Yes it'll create new string.
Any operation you do on string it'll create new string of it, because string is immutable type.

Dabbas
  • 3,112
  • 7
  • 42
  • 75
1

If you don't want to use ref you could change your signature from void to string and use it like this

public static string RemoveSpaces(string x)
{
   return x.Replace(" ","");
}

I think it's a matter of personal preference.

Kostis
  • 953
  • 9
  • 21
0

If you don't use ref, it wont work when you call that function.

string y = "Subash Kharel";
RemoveSpaces(y);
Console.Write(y);

The result will be "Subash Kharel" when you don't use ref.

H H
  • 263,252
  • 30
  • 330
  • 514
Subash Kharel
  • 478
  • 1
  • 3
  • 12
  • 1
    It is not explained very well, but the guy is right here. If you don't use the ref keyword in the call and **remove it** in the method you can't see the changes with y. – Steve Dec 27 '17 at 12:46