Saturday, December 9, 2023

String to Number conversion

In many scenarios we need to convert our data from one data type to another.

Most important one is converting a text (string) to number (int, float etc).

We can not assign a string data type int (or any number data types) directly.

Let's take the below code as an example

string t = "28";
int age = t;

It will cause the below compilation error

Cannot implicitly convert type 'string' to 'int'

Below are few ways to convert string to text

int age = int.Parse(t);

In case the content of the variable is not in correct format, it will cause a runtime error

The input string '{content}' was not in a correct format.

We can use TryParse method to fix this issue

string t = "28t";
bool isValid = int.TryParse(t, out var age);
if(isValid)
  Console.WriteLine(age);
else
  Console.WriteLine("Invalid data");

Parse and TryParse static methods are available in all numeric data types

No comments:

Post a Comment

Object Oriented Programming- 2- Inheritance

Inheritance is one of the fundamental attributes of object-oriented programming. It allows you to define a child class...