Lab: data types, continued
In the first half you stored values. In this half you move them from one type to another, which is where most beginner errors live.
Converting on purpose
C#
string typed = "25";
int age = System.Convert.ToInt32(typed);
int whole = 9;
double exact = whole; // safe, nothing is lostWhat to notice
- Text that looks like a number is still text until you convert it.
- Going from a whole number to a decimal number is safe.
- Going the other way can lose the decimal part, so it must be asked for explicitly.
What happens if the text is not a number. Conversion fails and throws an exception. In a web page that means a visitor can trigger an error just by typing letters, which is why validation matters.
Next, meet the operators that combine and compare values in the operators lab.