Reputation: 11237
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
Reputation: 38905
There are several ways to convert a string to an integer.
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.
Pretty much the same:
Dim b as Integer= Convert.ToInt32(b)
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
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