In-depth understanding of string transfer in C#
Strings in C# are reference types, but this often leads to misunderstandings. This article will delve into the subtleties of string passing and explain why the following code does not behave as expected:
<code class="language-csharp">class Test { public static void Main() { string test = "before passing"; Console.WriteLine(test); TestI(test); Console.WriteLine(test); } public static void TestI(string test) { test = "after passing"; } }</code>
Although the string is a reference type, the second output of this code has not changed. This is because of the distinction between passing references by value and passing objects by reference.
Passing a reference by value means copying the reference itself, any changes inside the method will not affect the original variable. Passing an object by reference will change the reference itself, and modifications within the method will be reflected in the original variable.
For strings to work as expected, they need to be passed by reference (using the ref
keyword):
<code class="language-csharp">using System; class Test { public static void Main() { string test = "before passing"; Console.WriteLine(test); TestI(ref test); Console.WriteLine(test); } public static void TestI(ref string test) { test = "after passing"; } }</code>
The modified code output is as follows:
<code>输入:before passing 输出:after passing</code>
This is not the same as modifying the underlying object. Strings in C# are immutable and their contents cannot be changed. However, we can pass an object by reference (e.g. StringBuilder
) and modify its data:
<code class="language-csharp">using System; using System.Text; class Test { public static void Main() { StringBuilder test = new StringBuilder(); Console.WriteLine(test); TestI(test); Console.WriteLine(test); } public static void TestI(StringBuilder test) { // 注意,我们没有改变 "test" 参数的值。 // 我们改变的是它所引用的对象中的数据。 test.Append("changing"); } }</code>
The output of this code is:
<code>输入: 输出:changing</code>
In summary, understanding the difference between passing a reference by value and passing an object by reference is crucial for working with strings in C#. By adopting appropriate methods, the expected behavior of the code can be achieved.
The above is the detailed content of Why Doesn't Modifying a String in a C# Method Change the Original String?. For more information, please follow other related articles on the PHP Chinese website!