Home >Backend Development >C++ >Are C# Arrays and Lists Passed by Value or by Reference?

Are C# Arrays and Lists Passed by Value or by Reference?

DDD
DDDOriginal
2025-01-10 11:45:42859browse

Are C# Arrays and Lists Passed by Value or by Reference?

Arrays and lists in C#: pass by reference or by value?

In C#, arrays and lists are passed by value. This means that when you pass these data structures as arguments to methods or functions, only copies of the references to them are passed.

Passed by value:

In .NET, arrays and lists are objects stored on the heap. When these objects are passed as arguments, references to their locations in memory are copied. This means that any changes made to the contents of an array or list are observable by the caller. However, if you reallocate the array or list itself (i.e. change the reference), these changes will not be detected by the caller.

Example:

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

Use ref for pass-by-reference:

If you need the caller to observe both content changes and reference reassignments, you can use the ref modifier. This will pass the reference by reference, ensuring that any modifications made to the reference itself are visible to the caller.

Example of using ref:

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

Thus, in C#, arrays and lists are passed by value by default. If you wish to pass the reference itself by reference, you can modify the method's signature to include the ref modifier.

The above is the detailed content of Are C# Arrays and Lists Passed by Value or by Reference?. 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