Why do we need too many methods that perform the same function?

string s1 = "1234"; 
string s2 = "1234.65"; 
string s3 = null; 
string s4 = "123456789123456789123456789123456789123456789";  

result = Int32.Parse(s1); //-- 1234
result = Int32.Parse(s2); //-- FormatException 
result = Int32.Parse(s3); //-- ArgumentNullException 
result = Int32.Parse(s4); //-- OverflowException 

result = Convert.ToInt32(s1); //-- 1234 
result = Convert.ToInt32(s2); //-- FormatException 
result = Convert.ToInt32(s3); //-- 0 
result = Convert.ToInt32(s4); //-- OverflowException 

success = Int32.TryParse(s1, out result); //-- success => true; result => 1234 
success = Int32.TryParse(s2, out result); //-- success => false; result => 0 
success = Int32.TryParse(s3, out result); //-- success => false; result => 0 
success = Int32.TryParse(s4, out result); //-- success => false; result => 0 

From this link

Why do we need these many conversion functions when the purpose of the operation is simply to convert the string to int.

I apologize if my question is stupid.

+3
source share
4 answers

They do 3 different things:

Int32.Parse()expects a string that is an exact representation of an integer. It is extremely limited - it either parses a string or explodes.

Int32.TryParse() - , Parse, . , , , , Parse, ( ). TryParse , , Parse.

Convert.ToInt32 - , , , int. () , , , IConvertible, ", - ".

+13

.

, TryParse , , , , null, .

+1

, .

, TryParse , , Try .

Convert vs Parse - convert Parse , null ( 0, a null ).

+1

Int32.Parse . .

Perhaps Int32.Parse is invoking Convert methods. But Convert is also a separate set of simple parsing methods. Since the exceptions are the same, I assume that it probably calls Convert methods.

As for TryParse methods, I would hardly say that they do the same job!

Also see this link

0
source

Source: https://habr.com/ru/post/1764226/


All Articles