How to convert string variable to int in c#?

Updated By: Amly | 14 May 2019

R

Rob

18 May 2019

To convert a string variable into int first of all we need to know that a string can be converted into int if that string contains only numbers for example 3545 or 3556 or 553121 or any string that contains only numbers. If a string which also contains other characters with or without number can not be converted into int for example 665a44 or 4345yrf45 etc. 

There are three ways to convert a string into int type, see blow example 

string num="546323";

int a;

1) a = Convert.ToInt32(num);

2) a = int.Parse(num)

3) Third way is the best way to convert string into int. In this method try to convert string into int and if conversion successful then it return True and result in out parameter and if it fails then it returns False see below 

bool isNum;

string num="543568";

int res;

isNum=int.TryParse(num, out res);

now we can check isNum variable, if it's value is true that's mean that conversion is successful and it is False then it denotes conversion not successful means that string can't be converted into int.

2 votes

R

Rakesh Mehata

24 May 2019

Agree with you @Rob, int.TryParse() method is the safest way to convert a string variable into int data type but it is bit slower than Convert.ToInt32()

0 votes

Your Answer

Email Us: advertise@gdatamart.com

Legal Policy

International

© 2022 GDATAMART.COM (All Rights Reserved)