Kredns
Kredns

Reputation: 37201

Casting in visual basic?

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?

Upvotes: 12

Views: 16090

Answers (5)

Lolu Omosewo
Lolu Omosewo

Reputation: 263

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

Therefore your code in VB.net is:

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

Upvotes: 0

Ben
Ben

Reputation: 3912

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

Upvotes: 2

JaredPar
JaredPar

Reputation: 754565

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")

Upvotes: 13

Andrew Hare
Andrew Hare

Reputation: 351466

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

Upvotes: 2

Adam Robinson
Adam Robinson

Reputation: 185593

C#:

(CheckBox)sender

VB:

CType(sender, CheckBox)

Upvotes: 19

Related Questions