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

2019-01-21 02:47发布

问题:

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 method can return a null value.
  • Use "Try" when the method will not throw an exception.

What is the official definition? What does "Try" say in the method name? Is there some official guideline about this?

回答1:

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.



回答2:

(Corrected) There is official guideline, as Erik suggested.

When I see TrySomething method, I assume it

  • doesn't throw
  • returns bool
  • if I expect value, it is returned via 'out' parameter
  • there exists Something method, that allows me to handle any exception myself. (edit, suggested by Jesse Webb)


回答3:

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
}


回答4:

You have to use "Try" in method name, when you want to manifest the fact that the method invokation can produce not valid result. Following the .NET standard it's, by the way, not a function that raises an exception, but the function that returns some VALID or NON_VALID, from the program perspective, value.

At the end, this all about naming convention you decide to use in your group.



回答5:

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.