What is the difference in C# between Convert.ToDecimal(string)
and Decimal.Parse(string)
?
In what scenarios would you use one over the othe
Knowing that Convert.ToDecimal is the way to go in most cases because it handles NULL, it, however, does not handle empty string very well. So, the following function might help:
'object should be a string or a number
Function ConvertStringToDecimal(ByVal ValueToConvertToDecimal As Object) As Decimal
If String.IsNullOrEmpty(ValueToConvertToDecimal.ToString) = False Then
Return Convert.ToDecimal(ValueToConvertToDecimal)
Else
Return Convert.ToDecimal(0)
End If
End Function
Convert.ToDecimal apparently does not always return 0. In my linq statement
var query = from c in dc.DataContext.vw_WebOrders
select new CisStoreData()
{
Discount = Convert.ToDecimal(c.Discount)
};
Discount is still null after converting from a Decimal? that is null. However, outside a Linq statement, I do get a 0 for the same conversion. Frustrating and annoying.
One factor that you might not have thought of is the Decimal.TryParse
method. Both Convert.ToDecimal
and Parse
throw exceptions if they cannot convert the string to the proper decimal format. The TryParse method gives you a nice pattern for input validation.
decimal result;
if (decimal.TryParse("5.0", out result))
; // you have a valid decimal to do as you please, no exception.
else
; // uh-oh. error message time!
This pattern is very incredibly awesome for error-checking user input.
Major Difference between Convert.ToDecimal(string)
and Decimal.Parse(string)
is that Convert handles Null
whereas the other throws an exception
Note: It won't handle empty string.
From bytes.com:
The Convert class is designed to convert a wide range of Types, so you can convert more types to Decimal than you can with Decimal.Parse, which can only deal with String. On the other hand Decimal.Parse allows you to specify a NumberStyle.
Decimal and decimal are aliases and are equal.
For Convert.ToDecimal(string), Decimal.Parse is called internally.
Morten Wennevik [C# MVP]
Since Decimal.Parse is called internally by Convert.ToDecimal, if you have extreme performance requirements you might want to stick to Decimal.Parse, it will save a stack frame.
There is one important difference to keep in mind:
Convert.ToDecimal
will return 0
if it is given a null
string.
decimal.Parse
will throw an ArgumentNullException
if the string you want to parse is null
.