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

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

    Make sure to include try in your methodname if:

    • you don't throw any exception
    • your method has the following signature: bool TrySomething(input, out yourReturn)

    So basically if we use try-methods we only get a boolean result back.

    So the following code will not throw any exceptions:

    string input = "blabla";
    int number;
    if (int.TryParse(input, out number))
    {
    // wooohooo we got an int!
    } else
    {
    //dooh!
    }
    

    Whereas this code can (and in this case will) throw exceptions:

    string input = "blabla";
    int number;
    try
    {
         number = int.Parse(input); //throws an exception
    }
    catch (Exception)
    {
         //dooh!
    }
    

    Using Try methods is a safer and more defensive way to code. Also the code snippet #2 takes more performance to execute if it's not an integer.

提交回复
热议问题