tags:

views:

329

answers:

4

I know an int is a value type, but what are arrays of value types? Reference types? Value types? I want to pass an array to a function to check something. Should I just pass the array, as it will just pass the reference of it, or should I pass it as ref?

+23  A: 

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.

http://msdn.microsoft.com/en-us/magazine/cc301755.aspx

Yannick M.
+3  A: 

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

http://msdn.microsoft.com/en-us/library/aa288453%28VS.71%29.aspx:

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

Joshua Tompkins
+2  A: 

The simlest test of reference type vs. value type is that reference type can be null, but value type can not.

Alex Reitbort
... except for nullable value types, which are nullable (you can set the value to null, which means the null value for the type rather than a null *reference*) and are still value types.
Jon Skeet
Never thought of doing that when trying to understand if they're value types or not! Great idea.
devoured elysium
+1  A: 

The array itself is a reference type. The values of that array are value or reference types as determined by the array data type. In your example, the array is a reference type and the values are value types.

All single-dimension arrays implicitly implement IList<T>, where <T> is the data type of the array. You can use that interface as the data type of your method parameter instead. You could also use IEnumerable<T> for the data type. In either case (or even if you just use int[]) you shouldn't need to explicitly pass it as a ref parameter.

Scott Dorman