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

C#Naming Conventions

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

(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)

Solution 3 - C#

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
}

Solution 4 - C#

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.

Solution 5 - C#

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.

Solution 6 - C#

Uncle Bob gives the example below in his book Clean Code. Whenever we expect an exception to be thrown we can use the Try prefix to a method name:

public void sendShutDown()
{
    try{
        tryToShutDown();
    } catch (DeviceShutDownError e) {
        logger.log(e);            
    }
}

And then (adapted):

private void tryToShutDown()
{
    //some code with no error handling, but
    //something might go wrong here
}

The tryToShutDown method does not make any error handling, because that's the responsibility of the sendShutDown method.

The TryParse pattern of Microsoft violates the clean code guideline that says that we should avoid output parameters.

If we're not developing a new version of C#, we don't have to stick to all Microsoft guidelines. Sometimes they're not the best.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionms007View Question on Stackoverflow
Solution 1 - C#Erik SchierboomView Answer on Stackoverflow
Solution 2 - C#nothrowView Answer on Stackoverflow
Solution 3 - C#Ashok DamaniView Answer on Stackoverflow
Solution 4 - C#TigranView Answer on Stackoverflow
Solution 5 - C#Fabian BiglerView Answer on Stackoverflow
Solution 6 - C#GlauberView Answer on Stackoverflow