Coder Perfect

When should “Try” be used in a C# method name?

Problem

We were debating with our coworkers about what it meant if a method’s name began with the word “Try.”

The following were some of the viewpoints:

What is the official meaning of the term? In the method name, what does “Try” mean? Is there any kind of official policy on this?

Asked by ms007

Solution #1

This is known as the TryParse pattern, and Microsoft has documented it. According to the official MSDN page on Exceptions and Performance:

The TryParse pattern makes sense if you have code that might throw an exception in a typical use case (for example, parsing an int).

Answered by Erik Schierboom

Solution #2

(Correction: As Erik noted, there is an official guideline.)

When I see the TrySomething method, I automatically believe it’s for testing.

Answered by nothrow

Solution #3

When you wish to move forward, I believe you should employ try. It makes no difference whether a method returns a value or not.

Case 1: if everything checks out, you can move forward.

Case 2: If it does not return, it is still fine; you can continue in another direction.

Use the out parameter if you expect a value as a result of that method.

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

Answered by Ashok Damani

Solution #4

When you want to show that the method invocation can generate an invalid result, you must use “Try” in the method name. By the way, according to the.NET standard, it’s not a function that throws an exception, but a function that returns a VALID or NON VALID value from the perspective of the program.

At the end of the day, it’s all about the name convention you choose for your organization.

Answered by Tigran

Solution #5

If you’re writing a method, make sure to include try in the name.

So, when we utilise try-methods, all we get is a boolean result.

As a result, the code below will not throw any exceptions:

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

This code, on the other hand, can (and will) throw exceptions:

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

Using Try methods is a more secure and protective approach of coding. Also, if the code snippet #2 is not an integer, it takes longer to execute.

Answered by Fabian Bigler

Post is based on https://stackoverflow.com/questions/17207712/when-is-try-supposed-to-be-used-in-c-sharp-method-names