C# CONCEPTS

C# Safer Type Conversion

Use of TryParse method for a safer type conversion

Sukhpinder Singh | .Net Developer
C# Programming
Published in
2 min readMay 6, 2021

--

Photo by Lukas from Pexels

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

--

--

Sukhpinder Singh | .Net Developer
C# Programming

Programmer by heart | C# | .Net 6 | .Net 8 | dotnet | dotnetcore | Kubernetes | Angular | AWS | Remember to 👏 Linktree: https://linktr.ee/sukhpindersingh