Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in C#.
To run the program, compile it and then execute the resulting executable:
In C#, the System namespace provides number parsing functionality. Unlike Go’s strconv package, C# uses methods on the respective numeric types (int.Parse, float.Parse, etc.) or the Convert class for more specific conversions.
C# doesn’t require specifying the bit size for parsing as it’s implicit in the method used (e.g., int.Parse for 32-bit integers, long.Parse for 64-bit integers).
For parsing hexadecimal numbers, C# uses the Convert.ToInt32 method with a base parameter, rather than inferring it from the string format.
Error handling in C# typically uses exceptions rather than returning error values. The try-catch block demonstrates how to handle parsing errors.
Next, we’ll look at another common parsing task: URLs.