In C #, string
is, rather, a type by reference. Strings
in C # are immutable, that is, you never actually change the value of a string
, but you get an altered copy that is then assigned to a variable. Example:
string s = "foo";
s = "bar";
What the above code does is create a copy of the string "foo", assign it the value "bar" and pass this new string
to the variable s
.
Because of this behavior, it is recommended to use C # StringBuilder
for string manipulation, thus avoiding the creation of multiple copies in memory.
More details here.
A simple way to solve the problem is to change the return type of the function ChangeText
to string and reassign the value of the variable text
to the return of the function:
public static void Main()
{
string text = "text";
text = ChangeText(text);
Console.WriteLine(text);
}
static string ChangeText(string text) {
text = "new text";
return text;
}
Functional sample in .NET Fiddle
Another alternative to solve by passing by reference would be to use the StringBuilder class from the C # default library:
public static void Main()
{
StringBuilder text = new StringBuilder("text");
Console.WriteLine(text);
ChangeText(text);
Console.WriteLine(text);
}
static void ChangeText(StringBuilder text) {
text.Replace(text.ToString(), "new text");
}
Functional sample in .NET Fiddle