lost_in_the_source
lost_in_the_source

Reputation: 11237

How to convert one data type to another

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?

Upvotes: 1

Views: 1408

Answers (2)

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.

Upvotes: 1

Oded
Oded

Reputation: 499352

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.

Upvotes: 1

Related Questions