c# .net

3 methods and efficiency of converting C# to int

3 methods and efficiency of converting C# to int, someone asked me to explain?


There are three ways to convert other types into integers in C#, int.Parse(), cast (int), and Convert.ToInt32(). Let's explore their respective features and efficiencies.

  1, int.Parse () method

  This method can only convert a character (string) to an integer (int). If you use it to convert a non-character to an int, an exception will be generated, for example:

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

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


  int text = int.Parse("turn to integer");


  This method converts an object into an integer (int). Since C# treats various data types as objects, it can convert all types to int; if it encounters a type that cannot be converted to int, it returns 0, for example:

    int n = Convert.ToInt32(Cache["totalOnline"]); // Transfer the object type to int

    bool flag = true; int b = Convert.ToInt32(flag); //turn boolean to int, return 0

    int m = Convert.ToInt32(null); //turn "empty" to int, return 0


 3, cast (int)

  Casting is usually used when the type to be converted is a clear number. Otherwise, an exception will be generated for a data type that cannot be converted to int, as shown in the following example:

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

 byte b = 8;

 int i = (int)b;

 Double d = 15.26;

 int i = (int)d; //the result is 15

4, efficiency comparison

  Since the Convert.ToInt32() method eventually calls the int.Parse() method first during the conversion process, the int.Parse() method is naturally more efficient than the Convert.ToInt32() method.

  If the type to be converted must be a number after conversion, it is recommended to use the int.Parse() method and cast (int) to improve program execution efficiency; if it cannot be determined, only use the Convert.ToInt32() method, or use Convert. The ToInt32() method adds exception handling, namely:

    int i;
                i = int.Parse(Cache["totalOnline"]);
                i = 0;



Post your comments / questions