Thursday, October 22, 2020

Old classic casting in C#

The classic difference between int.Parse(), Convert.ToInt32() and int.TryParse().

int.Parse(string s)

Simply, int.Parse (string s) method converts the string to integer. If string s is null, then it will throw ArgumentNullException. If string s is other than integer value, then it will throw FormatException. If string s represents out of integer ranges, then it will throw OverflowException

 

Convert.ToInt32(string s)

 Simply, Convert.ToInt32(string s) method converts the string to integer. If string s is null, then it will return 0 rather than throw ArgumentNullException. 

 If string s is other than integer value, then it will throw FormatException. If string s represents out of integer ranges, then it will throw OverflowException.

 

Int.TryParse(string s,Out)

Simply int.TryParse(string s,out int) method converts the string to integer out variable and returns true if successfully parsed, otherwise false. If string s is null, then the out variable has 0 rather than throw ArgumentNullException. If string s is other than integer value, then the out variable will have 0 rather than FormatException. If string s represents out of integer ranges, then the out variable will have 0 rather than throw OverflowException.

No comments: