C# Safer Type Conversion

C# CONCEPTS

Use of TryParse method for a safer type conversion

Photo by Lukas from Pexels


Learning Objectives

The article demonstrates

  1. TryParse() Method for safe conversion.

  2. Protect against the loss of data while casting.

Prerequisites

  1. Experience with data types like string, int, decimal, float, and so on.

  2. 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.

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

TryParse() method

It does numerous things concurrently:

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

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

  3. 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

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

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

  3. 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 Instagram Facebook Twitter

Stay tuned on C#

View at Medium.com

#TypeConversion #Csharp #DotnetCore #Dotnet #Programming

Recent Posts

See All

Design Pattern – Adapter

#Aspnetcore #AdapterDesignPattern #Csharp #DesignPatterns #Dotnet According to Gang of Four, the Adapter Pattern converts the interfaces of a class into interfaces that the client requires. In other w