[ACCEPTED]-Casting in visual basic?-casting

Accepted answer
Score: 19

C#:

(CheckBox)sender

VB:

CType(sender, CheckBox)

0

Score: 12

VB actually has 2 notions of casting.

  1. CLR style casting
  2. Lexical Casting

CLR 15 style casting is what a C# user is more 14 familiar with. This uses the CLR type system 13 and conversions in order to perform the 12 cast. VB has DirectCast and TryCast equivalent 11 to the C# cast and as operator respectively.

Lexical 10 casts in VB do extra work in addition to 9 the CLR type system. They actually represent 8 a superset of potential casts. Lexical 7 casts are easily spotted by looking for 6 the C prefix on the cast operator: CType, CInt, CString, etc 5 ... These cast, if not directly known by 4 the compiler, will go through the VB run 3 time. The run time will do interpretation 2 on top of the type system to allow casts 1 like the following to work

Dim v1 = CType("1", Integer)
Dim v2 = CBool("1")
Score: 2

Adam Robinson is correct, also DirectCast is available to you.

0

Score: 2

DirectCast will perform the conversion at 7 compile time but can only be used to cast 6 reference types. Ctype will perform the 5 conversion at run time (slower than converting 4 at compile time) but is obviously useful 3 for convertng value types. In your case 2 "sender" is a reference type so DirectCast 1 would be the way to go.

Score: 0

Casting in VB.net uses the keyword ctype. So 2 the C# statement (CheckBox)sender is equivalent to ctype(sender,CheckBox) in VB.net.

Therefore 1 your code in VB.net is:

if ctype(sender,CheckBox).Checked =True Then
    ' Do something...
else
    ' Do something else...
End If

More Related questions