When to use a Cast or Convert

前端 未结 9 2098
无人及你
无人及你 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: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.

提交回复
热议问题