Some of the suggestions, including the first part of the accepted answer, and the original question have a strong ability to return incorrect results, especially in the case of an exception.
The problem, and we have seen it many times, is that when you have one return value, minor changes in the logic of the method will inevitably lead to a path through the code that was not expected by the original author of the method and will cause the returned variable to be incorrect installed several times in the method or will not be installed at all.
Definitely when you need to collect a value to return to the caller and then complete some additional tasks in the subsequent method, but by and large this should be the exception, not the rule.
After tracking too many errors that were introduced as a result of the desire to have a single return value, our development standards now dictate that return will be used if absolutely necessary, and the reason for this should not be carefully documented in the code along with warnings for subsequent modifiers.
An additional advantage of this approach is that if the logic of the method is changed so that the new code path leads to a βholeβ in the return logic, you will be automatically notified about this by the compiler. Using a single return value, the developer must visually check every possible code path to ensure that nothing was missing.
Finally, instead of having a return value outside the exception, we require that the corresponding default value be returned from the exception handler. Thus, it is very clear what will happen in the event of an exception.
So, in our environment, your code will look like this:
public static string PingThatAddress(string hostAddress) { try { Ping ping = new Ping(); PingReply pingreply = ping.Send(hostAddress); if (pingreply != null && pingreply.Status.ToString() != "TimedOut") { return "Address: " + pingreply.Address + "\r" + "Roundtrip Time: " + pingreply.RoundtripTime + "\r" + "TTL (Time To Live): " + pingreply.Options.Ttl + "\r" + "Buffer Size: " + pingreply.Buffer.Length + "\r"; } else { return string.Empty; } } catch (Exception pingError) { Debug.Fail(pingError.Message + " " + pingError); return string.Empty; } }