Home >Backend Development >C++ >How Are Arrays Passed to Methods in C#?

How Are Arrays Passed to Methods in C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-10 10:47:41140browse

How Are Arrays Passed to Methods in C#?

In-depth understanding of array reference passing in C#

In C#, arrays are different from basic data types. They are reference types. This begs the question: how are arrays passed to methods? Pass by value or by reference?

Value passing

By default, array references are passed by value. This means that a copy of the reference is created and passed to the method. Changes made to the array contents inside the method will be visible to the calling code, but any reassignments to the array itself will not be propagated back to the caller.

Pass by reference

To modify the reference itself, you can use the ref modifier. Passing an array by reference allows the caller to see any changes to the reference, including reassignments.

Example

The following code demonstrates the difference between passing by value and passing by reference:

<code class="language-csharp">void Foo(int[] data) {
    data[0] = 1; // 调用方可见此更改
}
void Bar(ref int[] data) {
    data = new int[20]; // 调用方可见此更改
}</code>

When calling Foo, a copy of the reference is passed. Changing the contents of the array within Foo will be visible in the calling code. However, reassignments to arrays within Foo will not be seen by the caller.

In contrast, when calling ref with the Bar modifier, the reference itself is passed. Any changes to the reference, including reassignments, will be visible in the calling code.

The above is the detailed content of How Are Arrays Passed to Methods in C#?. 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