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

前端 未结 6 760
情书的邮戳
情书的邮戳 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:12

    I think you should use try when you want to proceed. It doesn't matter that a method returns some value or not.

    Case 1: if it returns fine, you can proceed in some way.

    Case 2: if it does not return: it is still fine; you can proceed in some other way.

    And if you expect some value as output of that method then use the out parameter.

    Example

    int value
    if (dictionary.TryGetValue("key", out value))
    {
        // Proceed in some way
    }
    else
    {
        // Proceed in some other way
    }
    

提交回复
热议问题