What are the pros and cons of using either of the following approaches to pulling out a double from an object? Beyond just personal preferences, issues I'm looking for feedback on include ease of debugging, performance, maintainability etc.
public static double GetDouble(object input, double defaultVal)
{
try
{
return Convert.ToDouble(input);
}
catch
{
return defaultVal;
}
}
public static double GetDouble(object input, double defaultVal)
{
double returnVal;
if (double.TryParse(input.ToString(), out returnVal))
{
return returnVal;
}
else
{
return defaultVal;
}
}
Try-Catch will always be the slower. TryParse will be faster. The IF and TryParse are the same. To be completely clear, Try-Catch will only be slower if the parse fails; not throwing/catching an exception doesn't cost anything.
The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed.
The C# try and catch keywords are used to define a try catch block. A try catch block is placed around code that could throw an exception. If an exception is thrown, this try catch block will handle the exception to ensure that the application does not cause an unhandled exception, user error, or crash the application.
TryParse
will be faster than catching an exceptionTryParse
indicates something expected - nothing exceptional is happening here, it's just that you suspect your data may not be valid.TryParse
isn't using exception handling for normal control flowBasically, go with TryParse
:)
By the way, your code can be rewritten as:
public static double GetDouble(object input, double defaultVal)
{
double parsed;
return double.TryParse(input.ToString(), out parsed)) ? parsed : defaultVal;
}
TryParse is more efficient than TryCatch performance wise.
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