Skip to main content
CSharpUniversity ASP.NET and C# lessons

The search runs entirely in your browser over the published lesson list.

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 lost

What 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.

New lessons by email

Leave your address and get a short note whenever a fresh lesson is published. No account needed and you can stop at any time.

Thank you. Your address has been noted in this browser session. Connect a mailing service to deliver the notes for real.