Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting in visual basic?

Tags:

c#

casting

vb.net

I'm a C# programmer who is forced to use VB (eh!!!!). I want to check multiple controls state in one method, in C# this would be accomplished like so:

if (((CheckBox)sender).Checked == true)
{
    // Do something...
}
else
{
    // Do something else...
}

So how can I accomplish this in VB?

like image 313
Kredns Avatar asked Apr 14 '09 18:04

Kredns


2 Answers

C#:

(CheckBox)sender

VB:

CType(sender, CheckBox)
like image 120
Adam Robinson Avatar answered Nov 12 '22 02:11

Adam Robinson


VB actually has 2 notions of casting.

  1. CLR style casting
  2. Lexical Casting

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

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

Dim v1 = CType("1", Integer)
Dim v2 = CBool("1")
like image 45
JaredPar Avatar answered Nov 12 '22 03:11

JaredPar