When is “Try” supposed to be used in C# method names?

前端 未结 6 785
情书的邮戳
情书的邮戳 2020-12-07 11:00

We were discussing with our coworkers on what it means if the method name starts with \"Try\".

There were the following opinions:

  • Use \"Try\" when the
6条回答
  •  孤街浪徒
    2020-12-07 11:25

    This is known as the TryParse pattern and has been documented by Microsoft. The official Exceptions and Performance MSDN page says:

    Consider the TryParse pattern for members that may throw exceptions in common scenarios to avoid performance problems related to exceptions.

    Thus if you have code for which a regular use case would mean that it might throw an exception (such as parsing an int), the TryParse pattern makes sense.

提交回复
热议问题