C# Safer Type Conversion

Sukhpinder Singh - May 14 '21 - - Dev Community

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.’
Enter fullscreen mode Exit fullscreen mode

To safeguard against this, use the TryParse() method on the target data type.

TryParse() method

It does numerous things concurrently:

  • Try to parse a string into a numeric data type.

  • If successful, it will save the converted value in an out parameter.

  • It returns a bool to show if it was successful.

Code snippet

The below example helps us to avoid runtime exception

string value = "Bob"; 
int result = 0; 
if (int.TryParse(value, out result)) {   
    Console.WriteLine($"Success: {result}"); 
} 
else {     
    Console.WriteLine("Failure."); 
}
Enter fullscreen mode Exit fullscreen mode

Note that the parsed value is stored in the int variable result. Variable is declared & initialized before the TryParse method to be accessible both inside and outside the code blocks.

Method properties/features

  • It returns false if it’s unsuccessful and true if the conversion was successful.

  • An out parameter provides a subsequent means of a method returning a value. In this instance, the out parameter returns the converted value.

  • Use the keyword **out **when passing in an argument to a method that has defined an out parameter.

Reference to an out parameter

Methods can return a value upon finish or return “void,” indicating they produce no value. Optionally, return values throughout parameters are defined just like any other parameters but include the out keyword.

When calling with an out parameter, it must also use the keyword out before the variable, which will hold the value.

int.TryParse(value, out result)
Enter fullscreen mode Exit fullscreen mode

Thank you for reading, and I hope you liked the article. Follow me on LinkedIn Instagram Facebook Twitter

Buy Me A Coffee

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .