Type conversion problem .

  • Thread starter Thread starter ann
  • Start date Start date
A

ann

Does somebody know why I get a blank string in strA? Last
time post the wrong code.

"
Option Strict On
Option Explicit On

Public Class Cast
Private Sub FuncA()

Dim strA As String
funcB(CType(strA, Integer))
MsgBox(strA)

End Sub

Public Sub funcB(ByRef objA As Integer)
objA = 1234
End Sub

End Class

"
 
Carl said:
Ann,
You are not getting the return value from the function call.
e.g.
strA = funcB(CType(strA, Integer))

No that's not correct. The function isn't returning anything in the
first place. Note that CType returns the result of the explicit
conversion of types.. so in fact, you should be storing that result in
another integer and passing that variable by reference to the function.
Observe:

Option Strict On
Option Explicit On

Public Class Cast
Private Sub FuncA()

Dim strA As String
Dim strB As Integer
strB = CType(strA, Integer)

funcB(strB)
MsgBox(strB)

End Sub

Public Sub funcB(ByRef objA As Integer)
objA = 1234
End Sub
End Class

If you don't do this, the object reference that you passed via:

funcB(CType(strA, Integer))

will be updated in funcB but on return of that routine, you lose that
object reference and are actually refering to the old reference to the
empty string object in the following line:

MsgBox(strA)

Hope that helps.

-Andre
 
Andre said:
No that's not correct. The function isn't returning anything in the
first place.

Doh! When I quickly scanned through the code, I "Func" in the name
and thought it was a Function. That's what I get for answering a post
before my first cup of coffee in the morning... ;-)

--

Thanks,
Carl Prothman
Microsoft ASP.NET MVP
http://www.able-consulting.com
 
Carl, my problem here is I want to pass a variable by
reference to a function which has a parameter in a
different type. Two way to do that :

1. Undre's way-- But it means more memory copy action.

2. Set strict OFF, then everything works fine except
there will no type checking.

So can you give some detail for Ctype()?
 
ann said:
Carl, my problem here is I want to pass a variable by
reference to a function which has a parameter in a
different type. Two way to do that :
1. Undre's way-- But it means more memory copy action.
2. Set strict OFF, then everything works fine except
there will no type checking.

I think your best bet is to NOT use a Sub / ByRef parameter,
but to create a Function that returns a value. That way you can do
the conversion on a ByVal parameter and not run into the ByRef
conversion problem.

If you do still want to use ByRef, then use Andre's technique,
which is right on the mark! I would not Set Strict Off.
So can you give some detail for Ctype()?

Here is what the on-line help says for CType:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vblr7/html/vafctCType.asp

--

Thanks,
Carl Prothman
Microsoft ASP.NET MVP
http://www.able-consulting.com
 
Back
Top