Difference between Convert.ToInt32, int.Parse and int.TryParse in C# .Net

Last Reply on Dec 15, 2014 04:32 AM By Azim

Posted on Dec 15, 2014 04:19 AM

What is the difference between these conversions ? Are they all same ? If no then what is the use of each?

1-

ConvertToInt32("10")

2-

int.Parse("10")

3-

- (int) "10"

4-

int.TryParse("10")
Posted on Dec 15, 2014 04:32 AM Modified on on Dec 15, 2014 07:05 AM

ConvertToInt32("10")

int i = Convert.ToInt32(null);

It can handle null values. If you run the above line you will get 0 in i variable.

int.Parse("10")

int i = int.Parse(null);

It cannot handle null. You will get this error Value cannot be null. Parameter name: String.

(int) "10"

You cannot directly convert string into int.

But you can convert double, float and decimal values like this

 In this below line you will get 10 only.

double s = 10.3;
int i = (int)s;

int.TryParse("10")

The above code line is not correct. It has to be written this way

int i;
int.TryParse("s", out i);
int value = i;

You will get 0 in variable value because s is not an integer value.

This above code will prevent us from error like input string is not in a correct format.