Home >Backend Development >C++ >Do C# Arrays and Lists Pass by Reference or by Value?

Do C# Arrays and Lists Pass by Reference or by Value?

Barbara Streisand
Barbara StreisandOriginal
2025-01-10 10:07:41869browse

Do C# Arrays and Lists Pass by Reference or by Value?

Passing array or list by reference in C#

Is an array or list in C# passed by reference or by value by default? This question often comes up when looking to optimize performance. Let's explore the answer and discuss whether passing by reference is a wise choice for efficiency.

Answer:

In C#, arrays and lists are passed by value, not by reference. This means that a reference to the array or list is copied into the function call, rather than the actual array or list itself.

When an array or list is passed to a function, the reference on the heap is copied to the stack. Changes made to the contents of the array or list within the function will be visible to the caller because the reference points to the same location in memory. However, any attempt to reassign the array or list itself (i.e. change the reference) will not be reflected in the caller's scope.

<code class="language-c#">void Foo(int[] data) {
    data[0] = 1; // 调用者可以看到此更改
}
void Bar(int[] data) {
    data = new int[20]; // 但看不到此更改
}</code>

In the above example, Foo modifies the first element of the array and this change is visible to the caller. However, Bar assigns a new array to data, which is invisible to the caller.

Use the 'ref' modifier to pass by reference

If you need the caller to see changes to the reference itself, you can use the ref modifier. When a parameter is passed by ref, the actual reference is passed, not a copy. This means that any changes to the reference within the function will be reflected in the caller's scope.

<code class="language-c#">void Foo(ref int[] data) {
    data = new int[20]; // 调用者可以看到此更改
}</code>

Optimization suggestions

While passing arrays or lists by reference may seem like a way to improve performance, it is generally not recommended. Passing by value ensures that any modifications to an array or list are localized within the function, preventing unintended changes to other parts of the program. Additionally, modern .NET optimizers can often handle pass-by-value efficiently without manual intervention.

The above is the detailed content of Do C# Arrays and Lists Pass by Reference or by Value?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn