undesirable explicit conversion behavior

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a function:

Public Sub Inverse(ByVal Source_Matrix As Double(,), ByRef
Destination_Matrix As Double(,))

Dim arrtemp(,) As Double = DirectCast(Source_Matrix, Double(,))
...........
For i = 1 To n
For j = n + 1 To 2 * n
arrtemp(i, j - n) = arrInv(i, j)
Next
Next
.......
End Function

"Source_Matrix" appears one time in this function - at the beginning as
shown above.

When the loop executes the array "Source_Matrix" changes to hold the new
values for arrtemp! (I know it occurs in this loop after step by step
execution).

The change carries through to the function caller. I don't think this is
quite right. It seems to me I made an initial assignment with the DirectCast
function (happens with CType also) not a permanent, unilateral marrage
between the two.

What's going on?

-
mark b
 
Do you really have to do the direct cast since Source_Matrix is already
declared as a parameter of double. Also, I think that only the reference to
Source_Matrix is passed and then when you make the assignment to arrtemp, you
also only assign the reference to the Source_Matrix array. Then when you
change arrtemp, it actualy changes Source_Matrix array. You might have to
set arrtemp values by looping thru all the Source_Matrix values and setting
arrtemp elements equal to each of them. Maybe the CopyTo method will work as
well.
 
mark said:
I have a function:

Public Sub Inverse(ByVal Source_Matrix As Double(,), ByRef
Destination_Matrix As Double(,))

Dim arrtemp(,) As Double = DirectCast(Source_Matrix, Double(,))

arrtemp and Source_Matrix now refer to the same array. There are not two
arrays: just one.

An array is a reference type. Not a value type, so assignments happen by
reference.

There is no need to pass the Destination_Matrix ByRef. just change this to
a Function returning Double(,).

Something like this:

Public Function Inverse(ByVal Source As Double(,)) As Double(,)
Dim N As Integer = Source.GetUpperBound(0)
Dim M As Integer = Source.GetUpperBound(1)
Dim Dest(M, N) As Double
For i As Integer = 0 To N - 1
For j As Integer = 0 To M - 1
Dest(j, i) = Source(i, j)
Next
Next
End Function

David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top