|
-
Apr 18th, 2006, 08:48 AM
#1
Thread Starter
Hyperactive Member
[3.0/LINQ] confused about passing arrays (byval or byref)
I was working on an example given from a book and I totally got confused.
Please correct me.
I was under the impression that in c# the default way of passing arrays (like any other element) is "byval".
If we don't mention any thing when passing an array to a method, what is the default way?
like
int[] firstarray = {32,33,34};
firstdouble(firstarray);
what is the difference between this way versus this way?
int[] secondarray = {22,23,22};
seconddouble(ref secondarray);
thanks
nath
-
Apr 18th, 2006, 09:51 AM
#2
Re: [3.0/LINQ] confused about passing arrays (byval or byref)
Arrays in .NET are reference type objects. Like all reference type objects, when you pass by value you can change the properties of the object and have the changes stick but you can't assign a new object to the variable and have that stick. When you pass by reference you can assign a new object to the variable and have that stick also. Execute this code to see the difference:
Code:
private void Form1_Load(object sender, EventArgs e)
{
int[] arr1 = { 1, 2, 3 };
int[] arr2 = { 1, 2, 3 };
int[] arr3 = { 1, 2, 3 };
int[] arr4 = { 1, 2, 3 };
MessageBox.Show(arr1[0].ToString());
MessageBox.Show(arr2[0].ToString());
MessageBox.Show(arr3[0].ToString());
MessageBox.Show(arr4[0].ToString());
this.ChangeElementByValue(arr1);
this.ChangeElementByReference(ref arr2);
this.ChangeArrayByValue(arr3);
this.ChangeArrayByReference(ref arr4);
MessageBox.Show(arr1[0].ToString()); // The value has changed.
MessageBox.Show(arr2[0].ToString()); // The value has changed.
MessageBox.Show(arr3[0].ToString()); // The value has not changed.
MessageBox.Show(arr4[0].ToString()); // The value has changed.
}
private void ChangeElementByValue(int[] arr)
{
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
}
private void ChangeElementByReference(ref int[] arr)
{
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
}
private void ChangeArrayByValue(int[] arr)
{
arr = new int[] { 10, 20, 30 };
}
private void ChangeArrayByReference(ref int[] arr)
{
arr = new int[] { 10, 20, 30 };
}
Last edited by jmcilhinney; Apr 18th, 2006 at 10:12 AM.
-
Apr 18th, 2006, 10:06 AM
#3
Thread Starter
Hyperactive Member
Re: [3.0/LINQ] confused about passing arrays (byval or byref)
Jim,
thanks for your detailed reply.
thats very helpful.
regards
nath
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|