Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is int[] a reference type or a value type?

Tags:

c#

.net

Arrays are mechanisms that allow you to treat several items as a single collection. The Microsoft® .NET Common Language Runtime (CLR) supports single-dimensional arrays, multidimensional arrays, and jagged arrays (arrays of arrays). All array types are implicitly derived from System.Array, which itself is derived from System.Object. This means that all arrays are always reference types which are allocated on the managed heap, and your app's variable contains a reference to the array and not the array itself.

https://msdn.microsoft.com/en-us/library/bb985948.aspx


The simplest test for reference type vs. value type is that reference types can be null, but value types can not.


Arrays (even of value types like int) are reference types in C#.

http://msdn.microsoft.com/en-us/library/aa288453(VS.71).aspx:

In C#, arrays are actually objects. System.Array is the abstract base type of all array types.


First I want to tell you that Array is a reference type. Why? I explain throw one example over here.

Example:

int val = 0; // this is a value type ok
int[] val1 = new int[20] // this is a reference type because space required to store 20 integer value that make array allocated on the heap.

Also reference types can be null whereas value types can't.

value type stored in Stack and reference type stored in Heap

You can pass array to function using out or ref. Only initialize methods are different.

more..