Friday, March 16, 2012

Option Strict Problem

I have the code below on a page with Option Strict on. The aCookie(0) part of the last line shows an compile error in VB designer of "Option Strict On disallows late binding.

I'm not doing any binding on the array, just grabbing an item from a cookie. What am I doing wrong here? Any help appreciated.

Dim aCookie As Array = CType(Split(aCookie1, ","),Array)
Dim IDCheck as Integer = CType(aCookie(0),Integer)
I'm guessing an Object (aCookie(0)) can't be cast to an Integer, try this in the CType instead aCookie(0).toString()
Thanks, but I tried

Dim IDCheck As Integer = CType(aCookie(0).ToString,Integer)

and it produces the same error.
Now I would say that aCookie(0) is null, casting a null value throws an exception.
I would suggest checking the EXACT contents of the cookie. I had major issues with using cookies on my site, mainly because of using them in an external class and tore my hair out until i found i was not looking at the right object.

Put a breakpoint on the line and a watch, see what you can find.
Failing that, i always found response.write useful for debugging
RE: aCookie(0) is null, casting a null value throws an exception.

Not the problem. If I turn option Strict off and run the page with a response write for aCookie(0), it produces the correct value.
What does
response.Write(aCookie(0).GetType.Fullname)
say the type is?
Bomberman, the cookie contents are as expected via response write

The contents are 2 items, like

5,mypassword

All I'm trying to do is set the first item - the 5 for example, to an integer.

Works ok with option strict off, but when On the error is that Option Strict On disallows late binding.

Am I missing something simple here, like maybe needing to bind something after getting the content of the cookie?
Mike, the response returns

System.String
Instead of a generic array... Use a string array...

Dim aCookie As Array = CType(Split(aCookie1, ","),Array)

dim aCookie() as String = split(aCookie1,",")


MSDN says

In addition to disallowing narrowing conversions, Option Strict generates an error for late binding. An object is late bound when it is assigned to a variable that is declared to be of type Object.

Since aCookie(0) reports a type of System.String and I'm using CType to conver to Integer, seems like this should work, bit it doesn't.
Here's the solution

Dim IDCheck As Integer = CType(aCookie.GetValue(0),Integer)

Note the GetValue after aCookie
You may want to use directcast in this case rather than CType. Its faster.
cmartyn, what do you mean by directcast? like CInt(myvariable)? I know that this would not work with my code and option strict as on.

When should CType be used as opposed to this other directcast?
You can't cast a string to integer. Use int.Parse instead.

0 comments:

Post a Comment