Reputation: 73
public static void Main()
{// do something here
String[] array1d = { "zero", "one", "two", "three" };
ShowArrayInfo(array1d);
PrintValues(array1d);
//do something here
}
public static void ShowArrayInfo(Array arr)
{//do something here}
public static void PrintValues( string[] myArr )
{//do something here}
In above code there are two different functions called
1. ShowArrayInfo
2. PrintValues
but the way array is collected in both the functions are different. In one, it is Array arr
and in another, it is int[] myArr
.
What is the difference between these two ways of collecting array , is arr
and myArr
are alike? Is arr
and myArr
reference to original array : array1d ? Can we perform same operations on myArr
as what we can perform on arr
?
Upvotes: 0
Views: 368
Reputation: 30062
Arrays are Reference types
, if you change elements in an array inside the function, this is reflected in the caller.
Array
is like a more generic class for dealing with arrays. check the example below.
Using Array
class, arr.GetValue(0)
return object
and not int
.
static void ChangeFirstItemToTen(int[] arr)
{
arr[0] = 10;
}
static void ChangeFirstItemToTen(Array arr)
{
arr.SetValue(10, 0);
}
static void Main(string[] args)
{
int[] values = new int[] { 5, 6, 7, 8 };
ChangeFirstItemToTen(values);
Console.WriteLine(values[0]); // prints 10;
}
Upvotes: 1
Reputation: 26233
Per the documentation, Array
is the base class for all arrays in the CLR.
You can also see from the documentation that there are far fewer methods and properties available on the base class. There aren't many reasons you'd reference an array using Array
instead of T[]
(int[]
, in this case).
In your example, both arr
and myArr
are references to the same array as array1d
. The main difference is the methods and properties available to you (though you could easily cast from one to the other).
Upvotes: 0
Reputation: 2433
Array
is the base class for all arrays in C#. The only difference in the two methods defined by you is one will accept array of any type and other of type int only. Both will have the 'pass by value' technique.
You can use 'pass by reference' by using the ref
keyword.
Upvotes: 0