In C#, string
is, yes, a type by reference. Strings
in C# are immutable, that is, you never really change the value of a string
and yes gets a modified copy which 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
for the variable s
.
Because of this behavior, it is recommended to use the StringBuilder
C# for string manipulation, thus preventing the creation of multiple copies in memory.
More details here.
A simple way to solve the problem posed would be to change the function return type ChangeText
to string and reassign the variable value text
with 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 example in . NET Fiddle
Another alternative to solve by reference would be using the Stringbuilder class from the standard C 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 example in . NET Fiddle
It would be better to give a better explanation, because the user seeks an explanation for the behavior presented, please supplement your question.
– Julio Borges