I don't like methods have several return lines. So I created a return value with string result - and in every condition I write result = something...
But when I write "try-catch" mechanism, I have to set public string result. Because, if I return a result in try, compiler will launch error, and says not all codes have return value. If I write result = string.Empty to end of the method, resharper says, it's not reachable code. So, here an example, and here is my question;
"What is the perfect way to write "return" in a method ?"
public static string PingThatAddress(string hostAddress)
{
try
{
Ping ping = new Ping();
PingReply pingreply = ping.Send(hostAddress);
string result;
if (pingreply != null && pingreply.Status.ToString() != "TimedOut")
{
result = "Address: " + pingreply.Address + "\r"
+ "Roundtrip Time: " + pingreply.RoundtripTime + "\r"
+ "TTL (Time To Live): " + pingreply.Options.Ttl + "\r"
+ "Buffer Size: " + pingreply.Buffer.Length + "\r";
}
else
{
result = string.Empty;
}
return result;
}
catch (Exception pingError)
{
Debug.Fail(pingError.Message + " " + pingError);
}
//compiler error: THERE IS NO RETURN VALUE here?
}
You could do it like this instead:
public static string PingThatAddress(string hostAddress)
{
string result = string.Empty;
try
{
Ping ping = new Ping();
PingReply pingreply = ping.Send(hostAddress);
if (pingreply != null && pingreply.Status.ToString() != "TimedOut")
{
result = "Address: " + pingreply.Address + "\r"
+ "Roundtrip Time: " + pingreply.RoundtripTime + "\r"
+ "TTL (Time To Live): " + pingreply.Options.Ttl + "\r"
+ "Buffer Size: " + pingreply.Buffer.Length + "\r";
}
}
catch (Exception pingError)
{
Debug.Fail(pingError.Message + " " + pingError);
}
return result;
}
Then just make sure result
is set to something that makes sense in the case of an exception.
If you are trying to stick with what Resharper is warning you about, do it this way:
public static string PingThatAddress(string hostAddress)
{
try
{
Ping ping = new Ping();
PingReply pingreply = ping.Send(hostAddress);
string result = string.Empty;
if (pingreply != null && pingreply.Status.ToString() != "TimedOut")
{
result = "Address: " + pingreply.Address + "\r"
+ "Roundtrip Time: " + pingreply.RoundtripTime + "\r"
+ "TTL (Time To Live): " + pingreply.Options.Ttl + "\r"
+ "Buffer Size: " + pingreply.Buffer.Length + "\r";
}
return result;
}
catch (Exception pingError)
{
Debug.Fail(pingError.Message + " " + pingError);
}
return string.Empty;
}
You can not have things both ways here: Your artificial standard not to have multiple return
statements is probably what is causing you to have trouble with Resharper.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With