Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make Convert.ChangeType() accept currency?

Tags:

c#

.net

NumberFormatInfo nfi = new NumberFormatInfo();
nfi.CurrencySymbol = "$";

var result1 = decimal.Parse("$123456", NumberStyles.Any, nfi).Dump(); // this works well
var result2 = Convert.ChangeType("$123456", typeof(decimal), nfi); // this doesn't work

I need Convert.ChangeType() to accept currency, is it possible? Tried setting NumberFormatInfo but looks like it ignores currency values.

like image 321
LINQ2Vodka Avatar asked Dec 16 '19 15:12

LINQ2Vodka


1 Answers

Convert is a static class and also ChangeType() is a static method, so you can not override them.

Even if this is not exactly what you have asked for, however, you may create your own class change the way you want it to work for decimal (and any others) and use Convert.ChangeType() as default for other types:

public static class MyConvert 
{
     public static object? ChangeType(object? value, Type conversionType, IFormatProvider provider)
     {
         if (conversionType == typeof(decimal))
             return decimal.Parse(value.ToString(), NumberStyles.Any, provider);
         else
             return Convert.ChangeType(value, conversionType, provider);
     }
} 

Now the following code would work as you expect:

var result2 = MyConvert.ChangeType("$123456", typeof(decimal), nfi);
like image 130
Ashkan Mobayen Khiabani Avatar answered Sep 20 '22 12:09

Ashkan Mobayen Khiabani