Parse v. TryParse

2018-12-31 20:27发布

What is the difference between Parse() and TryParse()?

int number = int.Parse(textBoxNumber.Text);

// The Try-Parse Method
int.TryParse(textBoxNumber.Text, out number);

Is there some form of error-checking like a Try-Catch Block?

8条回答
闭嘴吧你
2楼-- · 2018-12-31 20:39

Parse throws an exception if it cannot parse the value, whereas TryParse returns a bool indicating whether it succeeded.

TryParse does not just try/catch internally - the whole point of it is that it is implemented without exceptions so that it is fast. In fact the way it is most likely implemented is that internally the Parse method will call TryParse and then throw an exception if it returns false.

In a nutshell, use Parse if you are sure the value will be valid; otherwise use TryParse.

查看更多
长期被迫恋爱
3楼-- · 2018-12-31 20:46

TryParse does not return the value, it returns a status code to indicate whether the parse succeeded (and doesn't throw an exception).

查看更多
与风俱净
4楼-- · 2018-12-31 20:50

TryParse and the Exception Tax

Parse throws an exception if the conversion from a string to the specified datatype fails, whereas TryParse explicitly avoids throwing an exception.

查看更多
查无此人
5楼-- · 2018-12-31 20:52

I know its a very old post but thought of sharing few more details on Parse vs TryParse.

I had a scenario where DateTime needs to be converted to String and if datevalue null or string.empty we were facing an exception. In order to overcome this, we have replaced Parse with TryParse and will get default date.

Old Code:

dTest[i].StartDate = DateTime.Parse(StartDate).ToString("MM/dd/yyyy");
dTest[i].EndDate = DateTime.Parse(EndDate).ToString("MM/dd/yyyy");

New Code:

DateTime startDate = default(DateTime);
DateTime endDate=default(DateTime);
DateTime.TryParse(dPolicyPaidHistories[i].StartDate, out startDate);
DateTime.TryParse(dPolicyPaidHistories[i].EndDate, out endDate);

Have to declare another variable and used as Out for TryParse.

查看更多
宁负流年不负卿
6楼-- · 2018-12-31 20:56

For the record, I am testing two codes: That simply try to convert from a string to a number and if it fail then assign number to zero.

        if (!Int32.TryParse(txt,out tmpint)) {
            tmpint = 0;
        }

and:

        try {
            tmpint = Convert.ToInt32(txt);
        } catch (Exception) {
            tmpint = 0;
        }

For c#, the best option is to use tryparse because try&Catch alternative thrown the exception

A first chance exception of type 'System.FormatException' occurred in mscorlib.dll

That it is painful slow and undesirable, however, the code does not stop unless Debug's exception are settled for stop with it.

查看更多
琉璃瓶的回忆
7楼-- · 2018-12-31 20:57

If the string can not be converted to an integer, then

  • int.Parse() will throw an exception
  • int.TryParse() will return false (but not throw an exception)
查看更多
登录 后发表回答