Casting in visual base?

I am a C # programmer who is forced to use VB (eh !!!!). I want to check the status of several controls in one way, in C # this will be done as follows:

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

So how can I accomplish this in VB?

+6
casting c #
source share
5 answers

FROM#:

 (CheckBox)sender 

VB:

 CType(sender, CheckBox) 
+15
source share

VB actually has 2 concepts of casting.

  • CLR casting
  • Lexical casting

CLR style casting is something that is more familiar to a C # user. It uses a CLR type and conversion system to perform the cast. VB has DirectCast and TryCast equivalent to the C # operator and as the operator, respectively.

VB lexical throws do extra work in addition to a CLR type system. They are actually a superset of potential castings. Lexical drops are easily recognized when looking for the C prefix in the casting operator: CType, CInt, CString, etc. These castings, if they are not directly known to the compiler, will go through VB runtime. Runtime will interpret on top of the type system to allow the following actions to be performed:

 Dim v1 = CType("1", Integer) Dim v2 = CBool("1") 
+10
source share

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

+2
source share

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

+2
source share

The VB.net role uses the ctype keyword. So the C # operator (CheckBox)sender equivalent to ctype(sender,CheckBox) in VB.net.

Therefore, your code in VB.net:

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

All Articles