C# Safer Type Conversion
Tags: csharp, dotnet, oop, beginners
Published: 2021-05-14 03:23:39

## 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](https://visualstudio.microsoft.com/downloads/).

## 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.’

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."); 
    }

**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)

Thank you for reading, and I hope you liked the article. Follow me on [LinkedIn](https://www.linkedin.com/in/sukhpinder-singh-532284a2/) [Instagram](https://www.instagram.com/sukhpindersukh/) [Facebook](https://www.facebook.com/sukhpinder.singh.52/) [Twitter](https://twitter.com/sukhsukhpinder)

<a href="https://www.buymeacoffee.com/sukhpindersingh" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Coffee" style="height: 41px !important;width: 174px !important;box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;-webkit-box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;" ></a>