The Convert Class and Parsing
Parse and convert with Convert and TryParse.
Converting Strings to Numbers
User input arrives as text. To compute with it you must convert strings to numbers. C# offers Convert, Parse, and TryParse.
using System;
class Program
{
static void Main()
{
string input = "42";
int number = int.Parse(input);
Console.WriteLine(number + 8);
}
}int.Parse
int.Parse turns a numeric string into an int. It throws a FormatException if the text is not a valid number.
using System;
class Program
{
static void Main()
{
try
{
int n = int.Parse("abc");
Console.WriteLine(n);
}
catch (FormatException)
{
Console.WriteLine("Not a valid number");
}
}
}All lessons in this course
- Value Types vs Reference Types
- Boxing and Unboxing
- Implicit and Explicit Conversions
- The Convert Class and Parsing