Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# implicit conversions

I'm currently working on an application where I need to load data from an SQL database and then assign the retrieved values into the properties of an object. I'm doing this by using reflection since the property names and column names are the same. However, many of the properties are using a custom struct type that is basically a currency wrapper for the decimal type. I have defined an implicit conversion in my struct:

public static implicit operator Currency(decimal d)
{
     return new Currency(d);
}

This works fine when I use it in code. However, when I have this:

foreach (PropertyInfo p in props)
{
     p.SetValue(this, table.Rows[0][p.Name], null);
}

It throws an ArgumentException stating that it cannot convert from System.Decimal to Currency. I'm confused since it works fine in any other circumstance.

like image 505
Chris Boden Avatar asked May 05 '10 19:05

Chris Boden


2 Answers

Unfortunately, these user-defined conversion operators are not used by the runtime; they are only used by the compiler at compile time. So if you take a strongly-typed decimal and assign it to a strongly-typed Currency, the compiler will insert a call to your conversion operator and everybody's happy. However, when you call SetValue as you're doing here, the runtime expects you to give it a value of the appropriate type; the runtime has no idea that this conversion operator exists, and won't ever call it.

like image 193
Charlie Avatar answered Sep 24 '22 07:09

Charlie


I think you need to first unbox the value in table.Rows[0][p.Name] as a decimal.

In other words:

foreach (PropertyInfo p in props)
{
     if (p.PropertyType == typeof(Currency))
     {
         Currency c = (decimal)table.Rows[0][p.Name];
         p.SetValue(this, c, null);
     }
     else
     {
         p.SetValue(this, table.Rows[0][p.Name], null);
     }
}

This is an issue I've seen once or twice before, so I actually decided to write a blog post about it. Anybody looking for a little more explanation, feel free to give it a read.

like image 22
Dan Tao Avatar answered Sep 22 '22 07:09

Dan Tao