Double.TryParse or Convert.ToDouble - which is faster and safer?

前端 未结 11 1002
滥情空心
滥情空心 2020-11-28 07:28

My application reads an Excel file using VSTO and adds the read data to a StringDictionary. It adds only data that are numbers with a few digits (1000 1000,2 10

11条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 07:56

    Unless you are 100% certain of your inputs, which is rarely the case, you should use Double.TryParse.

    Convert.ToDouble will throw an exception on non-numbers
    Double.Parse will throw an exception on non-numbers or null
    Double.TryParse will return false or 0 on any of the above without generating an exception.
    

    The speed of the parse becomes secondary when you throw an exception because there is not much slower than an exception.

提交回复
热议问题