When to use a Cast or Convert

前端 未结 9 2046
无人及你
无人及你 2020-11-30 00:45

I am curious to know what the difference is between a cast to say an int compared to using Convert.ToInt32(). Is there some sort of performance gai

相关标签:
9条回答
  • 2020-11-30 01:22

    string number = "123abc";

    int num;

    Int32.TryParse(number, out num); // no exception thrown at this call

    Convert.ToInt32(number); // exception IS thrown at this call

    0 讨论(0)
  • 2020-11-30 01:29

    Cast when it's really a type of int, Convert when it's not an int but you want it to become one.

    For example int i = (int)o; when you know o is an int

    int i = Convert.ToInt32("123") because "123" is not an int, it's a string representation of an int.

    0 讨论(0)
  • 2020-11-30 01:29

    There are a lot of overloads for Convert.ToInt32 that can take for example a string. While trying to cast a string to an int will throw a compile error. The point being is they're for different uses. Convert is especially useful when you're not sure what type the object you're casting from is.

    0 讨论(0)
  • 2020-11-30 01:35

    There is one more reason you should use Convert.ToInt32 instead of a cast.

    For example:

    float a = 1.3f;
    float b = 0.02f;
    int c = (int)(a / b);
    int d = Convert.ToInt32(a / b);`
    

    The result is c = 64 and d = 65

    0 讨论(0)
  • 2020-11-30 01:36

    See Diff Between Cast and Convert on another forum

    Answer

    The Convert.ToInt32(String, IFormatProvider) underneath calls the Int32.Parse (read remarks).
    So the only difference is that if a null string is passed it returns 0, whereas Int32.Parse throws an ArgumentNullException.
    It is really a matter of choice whichever you use.

    Personally, I use neither, and tend to use the TryParse functions (e.g. System.Int32.TryParse()).


    UPDATE

    Link on top is broken, see this answer on StackOverflow.

    0 讨论(0)
  • 2020-11-30 01:36

    There is another difference. "Convert" is always overflow-checked, while "cast" maybe, depending on your Settings and the "checked" or "unchecked" keyword used.

    To be more explicit. Consider the code:

    int source = 260;
    byte destination = (byte)source;
    

    Then destination will be 4 without a warning.

    But:

    int source = 260;
    byte destination = Convert.ToByte(source);
    

    will give you a exception.

    0 讨论(0)
提交回复
热议问题