C# CONCEPTS
C# Safer Type Conversion
Use of TryParse method for a safer type conversion
Published in
2 min readMay 6, 2021
Learning Objectives
The article demonstrates
TryParse()
Method for safe conversion.- Protect against the loss of data while casting.
Prerequisites
- Experience with data types like string, int, decimal, float, and so on.
- Install latest visual studio community edition.
Getting Started
When working with data, you’ll likely need to convert string data into a numeric data type. The string data type can handle a non-numeric value, and it’s possible that performing a conversion from a string into a numeric data type will prompt a runtime error.
For example, the following code snippet:
In this scenario, a wrong value that cannot be converted into an int, given intentionally.
string name = “Bob”;
Console.WriteLine(int.Parse(name));#Causes the following exception
#System.FormatException: ‘Input string was not in a correct format.’