Are you expecting users of different 'cultures' to use your application? If so it's better to factor in the user's regional settings:
static decimal ToDecimal(this string str)
{
return Decimal.Parse(str, CultureInfo.CurrentCulture);
}
Or you could replace every character in str that isn't a digit or the CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator
value and then parse it as a decimal.
EDIT:
It is generally accepted that extension methods should have their own namespace. This will avoid naming conflicts and force the end user to selectively import the extensions they need.
Aside:
Extension methods can help you to write clean and elegant looking code but personally I prefer not to use them because they only seem to be half finished, a bit of a hack to get Linq working:
- You can't create static extension methods. Do you like the
String.IsNullOrEmpty
method? Well you can't use that pattern in other classes. You can try but rather than having MyType.IsNullOrEmpty(myVar)
you'll end up with something like myVar.IsNullOrEmpty()
which leads to my next point...
- Under normal circumstances, if
myVar == null
, the above code wouldn't work - it would give you a run time exception for trying to call a method on an uninstatiated object. In the case of extension methods it still works though, which leads to inconsistencies in your code. I hate inconsistencies in my code.