Efficiency of C# convert string,object,bool and byte to int(3 methods)

Lionsure 2020-07-22 Original by the website

There are three methods to convert other types to int in C#, namely int.Parse(), coercion(int) and Convert.ToInt32(). The following discusses their respective characteristics and efficiency.

 

1. int.Parse() (C# convert string to int)

This method can only convert string to int. If you use it to convert a non-string to an int, an exception will be generated. Examples are as follows:

int i = int.Parse("100");

Note: If you convert a character that cannot be converted to int to int, an exception will also occur, such as:

int text = int.Parse("C# convert string to int");

 

2. Convert.ToInt32() (C# convert object to int)

This method is to convert object to int. Since C# treats various data types as objects, all types can be converted to int; when it encounters a type that cannot be converted to int, it returns 0, for example as follows:

int n = Convert.ToInt32(Cache["totalOnline"]); //C# convert object to int

bool flag = true;
       int b = Convert.ToInt32(flag); //Convert bool to int in c#, the result returns 0

int m = Convert.ToInt32(null);//Convert null to int, the result returns 0

 

3. Coerced conversion(int)

Coerced conversion is usually used when the type to be converted is a relatively clear number after the conversion, otherwise the data type that cannot be converted to int will cause an exception when using a coercive conversion, for example:

int n = (int)Cache["totalOnline"]; //Convert the cached online number to int

byte b = 8;
       int i = (int)b;//C# convert byte to int

double d = 15.26;
       int i = (int)d; //The result is 15

 

4. Comparison of efficiency

The Convert.ToInt32() finally calls the int.Parse() first in the conversion process, so the int.Parse() is naturally more efficient than the Convert.ToInt32().

If the type to be converted must be a number after conversion, it is recommended to use the int.Parse() and coercion(int) to improve the execution efficiency of program; if you cannot determine, you can only use the Convert.ToInt32(), or use Convert.ToInt32() plus exception handling, namely:

int i;
       try
       {
              i = int.Parse(Cache["totalOnline"]);
       }
       catch
       {
              i = 0;
       }