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 21:00

double.Parse("-"); raises an exception, while double.TryParse("-", out parsed); parses to 0 so I guess TryParse does more complex conversions.

查看更多
泪湿衣
3楼-- · 2018-12-31 21:03

The TryParse method allows you to test whether something is parseable. If you try Parse as in the first instance with an invalid int, you'll get an exception while in the TryParse, it returns a boolean letting you know whether the parse succeeded or not.

As a footnote, passing in null to most TryParse methods will throw an exception.

查看更多
登录 后发表回答