What is the difference between Convert.ToInt32 and (int)?

后端 未结 12 1496
星月不相逢
星月不相逢 2020-11-27 03:11

The following code throws an compile-time error like

Cannot convert type \'string\' to \'int\'

string name = Session[\"name1\"].ToString();
int i = (         


        
相关标签:
12条回答
  • 2020-11-27 03:44

    Just a brief extra: in different circumstances (e.g. if you're converting a double, &c to an Int32) you might also want to worry about rounding when choosing between these two. Convert.Int32 will use banker's rounding (MSDN); (int) will just truncate to an integer.

    0 讨论(0)
  • 2020-11-27 03:45

    A string cannot be cast to an int through explicit casting. It must be converted using int.Parse.

    Convert.ToInt32 basically wraps this method:

    public static int ToInt32(string value)
    {
        if (value == null)
        {
            return 0;
        }
        return int.Parse(value, CultureInfo.CurrentCulture);
    }
    
    0 讨论(0)
  • 2020-11-27 03:50

    You're talking about a C# casting operation vs .NET Conversion utilities

    • C# Language-level casting uses parenthesis - e.g. (int) - and conversion support for it is limited, relying on implicit compatibility between the types, or explicitly defined instructions by the developer via conversion operators.
    • Many conversion methods exist in the .NET Framework, e.g. System.Convert, to allow conversion between same or disparate data types.

    (Casting) syntax works on numeric data types, and also on "compatible" data types. Compatible means data types for which there is a relationship established through inheritance (i.e. base/derived classes) or through implementation (i.e. interfaces).

    Casting can also work between disparate data types that have conversion operators defined.

    The System.Convert class on the other hand is one of many available mechanisms to convert things in the general sense; it contains logic to convert between disparate, known, data types that can be logically changed from one form into another.

    Conversion even covers some of the same ground as casting by allowing conversion between similar data types.


    Remember that the C# language has its own way of doing some things.
    And the underlying .NET Framework has its own way of doing things, apart from any programming language.
    (Sometimes they overlap in their intentions.)

    Think of casting as a C# language-level feature that is more limited in nature, and conversion via the System.Convert class as one of many available mechanisms in the .NET framework to convert values between different kinds.

    0 讨论(0)
  • 2020-11-27 03:50

    This is already discussed but I want to share a dotnetfiddle.

    If you are dealing with arithmetic operations and using float, decimal, double and so on, you should better use Convert.ToInt32().

    using System;
    
    public class Program
    {
      public static void Main()
      {
        double cost = 49.501;
        Console.WriteLine(Convert.ToInt32(cost));
        Console.WriteLine((int)cost);
      }
    }
    

    Output

    50
    49
    

    https://dotnetfiddle.net/m3ddDQ

    0 讨论(0)
  • 2020-11-27 03:51

    (int)foo is simply a cast to the Int32 (int in C#) type. This is built into the CLR and requires that foo be a numeric variable (e.g. float, long, etc.) In this sense, it is very similar to a cast in C.

    Convert.ToInt32 is designed to be a general conversion function. It does a good deal more than casting; namely, it can convert from any primitive type to a int (most notably, parsing a string). You can see the full list of overloads for this method here on MSDN.

    And as Stefan Steiger mentions in a comment:

    Also, note that on a numerical level, (int) foo truncates foo (ifoo = Math.Floor(foo)), while Convert.ToInt32(foo) uses half to even rounding (rounds x.5 to the nearest EVEN integer, meaning ifoo = Math.Round(foo)). The result is thus not just implementation-wise, but also numerically not the same.

    0 讨论(0)
  • 2020-11-27 03:55

    1) C# is type safe language and doesn't allow you to assign string to number

    2) second case parses the string to new variable. In your case if the Session is ASP.NET session than you don't have to store string there and convert it back when retrieving

    int iVal = 5;
    Session[Name1] = 5;
    int iVal1 = (int)Session[Name1];
    
    0 讨论(0)
提交回复
热议问题