简体   繁体   中英

Casting or Parsing of Text in vb.net

in vb, you can use text which is in textbox instead of numerical expressions. I mean, if I write 50 in textbox1 and also I can write like that code:

 Dim result As Double = TextBox1.Text + 0.4

as you see, I didnt convert any type but it works in vb.net

But I want to learn what are disadvantages of this using?

(I am just talking about arithmetic operations)

Under the hood VB.net is doing an implicit narrowing conversion of TextBox1.Text (ie CType(TextBox1.Text, Double) ) to make that work. This means you have Option Strict off . Probably the biggest disadvantage to doing this is you would be going against the best practice of having Option Strict On.

By having Option Strict off you are preventing the compiler from enforcing type checking. This allows you to code in a more VB6 way. So implicit conversions of narrowing scope are allowed. If you had turned it on, only widening conversions (which don't have the potential of negative side affects) are allowed.

While in this specific scenario, it may not seem to be a big deal, but leaving it off for your whole codebase likely will result in subtle bugs creeping in.

I'd suggest reading about Widening and Narrowing Conversions (Visual Basic) on MSDN .

In VB.NET you will only get away with this if you have OPTION STRICT turned off - otherwise, you'll generate an error.

In programmming, you should always try to be as precise as possible with your data types. So you could write your line of code as:

Dim result as Double = Convert.ToDouble(TextBox1.Text) + 0.4

Alternatively, you could do some error trapping:

Dim Result as Double
Try
Result = Convert.ToDouble(TextBox1.Text) + 0.4
Catch
Result = 0
End Try

There are a lot of other things you can use, include TryParse. You can even use VBA functions like CDbl too.

If you rely on what is called implicit type conversion, VB.NET will attempt to convert the data type for you. The disadvantage of this approach is that it makes for lazy programming. On this occasion you want VB.NET to be fault-tolerant, but how about when you don't? If you allow it to correct your errors, you'll eventually get the situation where you generate bugs because your code isn't enforcing the correct data type.

Right - that's the party line over. Personally, I quite like the way VBA casts data types behind the scenes for me!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM