You can use the Parse method to convert a string that represents a number to its equivalent numerical representation.
1 2 | string numberString = "108" ; int number = <span class = "skimlinks-unlinked" > int .Parse(numberString</span>); |
If the string does not represent a value of the associated numeric type, or represents a numeric value that is outside the range of the type, a FormatException or OverflowException is generated.
1 | int n1 = <span class = "skimlinks-unlinked" > int .Parse( "3.4</span>" ); // FormatException |
You can avoid the exception by using the TryParse method. If the parse operation succeeds, the parsed value is stored in the output parameter and TryParse returns true. If the parse operation does not succeed, the output parameter is not written to and TryParse returns false. No exception is thrown.
1 2 3 4 5 | int n1; if ( int .TryParse( "3.4" , out n1)) Console.WriteLine( "Parse worked--n1 contains number" ); else Console.WriteLine( "Can't parse" ); |