Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing by ref ?

Status
Not open for further replies.

StevenK

Programmer
Jan 5, 2001
1,294
GB
I have a procedure that copies the contents of one Array List to another (as long as the dimensions are the same). The code is as follows :

private bool CopyArrListToArrList(object [,] arrList1, object [,] arrList2)
{
//-------------------------------------------------------
// This copies the elements from arrList1 --> arrList2.
//-------------------------------------------------------
bool ok = false; // Set to true on completion
// Need to check that the Array List dimensions are the same
int dim1Int1 = arrList1.GetLength(0);
int dim2Int1 = arrList1.GetLength(1);
int dim1Int2 = arrList2.GetLength(0);
int dim2Int2 = arrList2.GetLength(1);
if ((dim1Int1 == dim1Int2) && (dim2Int1 == dim2Int2))
{
try
{
for (int i = 0; i < dim1Int1; i++)
{
for (int j = 0; j < dim2Int1; j++)
{
arrList2[i, j] = arrList1[i, j];
}
}
// If we have got here then all worked OK.
ok = true;
}
catch (Exception eCopy)
{
// Something went wrong
MessageBox.Show(&quot;Failure in 'CopyArrListToArrList' copying\n\n&quot; + eCopy.ToString());
}
}
else
{
// Dimensions are not the same so unable to copy
MessageBox.Show(&quot;Failure in 'CopyArrListToArrList' due to dimensions.\n\n&quot; +
&quot;arrList1.GetLength(0) : &quot; + dim1Int1.ToString() + &quot;\n&quot; +
&quot;arrList1.GetLength(1) : &quot; + dim2Int1.ToString() + &quot;\n&quot; +
&quot;arrList2.GetLength(0) : &quot; + dim1Int2.ToString() + &quot;\n&quot; +
&quot;arrList2.GetLength(1) : &quot; + dim2Int2.ToString());
}
return ok;
}

This allows the setting of elements in the 'arrList2' albeit that I have not passed the array list by reference (defined by 'ref' ?).

Should this be the case ?

Ideally I want to be able to change the contents of the 'arrList2' array list but not be able to change the contents of the 'arrList1' array list (I'm guessing that this procedure as it stands will let me change elements in this one too ?).
How should I define these array lists in the scope of the passed parameters to ensure that this is the case ?

I'm new to C# so any pointers would be appreciated.
Thanks in advance

Steve
 
I don't think you can restrict access to arrays like this, as arrays are reference types (not value types), and always get passed byref.

Chip H.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top