1

I am a very novice VB.NET programmer. How do I convert one type to another?

Dim a as String="2"
Dim b as Integer='what?
lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75

2 Answers2

1

Many of the "primitive" data types have several parsing methods that can construct from a string representation.

Check the Parse and TryParse shared methods of Integer.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
1

There are several ways to convert a string to an integer.

  1. You know the string contains a numeric:

    Dim b as Integer = Integer.Parse(a) 
    

    If it is not a valid integer or contains non numerals, it can crash. Other value types (Decimal, Double) have the same method.

  2. Pretty much the same:

    Dim b as Integer= Convert.ToInt32(b) 
    
  3. You dont know if the string is clean or not. For instance this would be used to convert a value from a text box, where the user types "cat" as their age:

    If Integer.TryParse(a, b) Then ...
    

The big difference here is that the return is a Boolean (True or False) telling you whether the parsing went ok. If not (False), tell the user to enter again; else (True) the second param will be the converted value. Date, Double, Decimal etc all have a TryParse method.

This answer provides a more detailed explanation.

Community
  • 1
  • 1
Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178