Is int[]
in C# a reference type or a value type?
In C#, basic data types like int
are value types. They are stored directly in variables and their values are copied when passed to methods or assigned to other variables.
However, arrays of value types behave differently. Even if the elements of the array are value types, the array itself is a reference type. This is because the array reference points to the memory location where the array elements are stored, not the elements themselves.
Impact on function calls
When passing an array to a function, there is no need to specify the ref
or out
modifier because arrays are passed by reference by default.
Functions that receive an array can only access a reference to the array, not the actual elements. If the function modifies elements, those changes will be reflected in the original array.
Example:
Consider the following code:
<code class="language-csharp">int[] array = { 1, 2, 3 }; ModifyArray(array); Console.WriteLine(array[0]); // 输出:4</code>
ModifyArray
The function modifies the first element of the array:
<code class="language-csharp">public static void ModifyArray(int[] arr) { arr[0] = 4; }</code>
Even if we pass the array by value (without the ref
modifier), the changes made in the function will be reflected in the original array because the array is a reference type.
The above is the detailed content of Is an Array of Value Types (e.g., `int[]`) a Reference Type or a Value Type in C#?. For more information, please follow other related articles on the PHP Chinese website!