472,960 Members | 1,893 Online

# ArrayTypeMismatchException

Hello!

This simple code:

decimal[] a = new decimal[] { 23.45m, 120.0m };
double[] b = new double[2];

a.CopyTo(b, 0);

throws an ArrayTypeMismatchException. I can't find anything in the docs
which suggests that this is expected behaviour. Can anybody please give me
an explanation for it?

--
Thank you,

Christopher Ireland

"There is no way to peace; peace is the way."
A. J. Muste

Sep 12 '08 #1
6 1977
http://msdn.microsoft.com/en-us/library/06x742cw.aspx

"ArrayTypeMismatchException
The type of the source Array cannot be cast automatically to the type of
the destination array."

In this case, there is no automatic conversion between decimal and
double - they are very different data types. Suggest you just loop? Or use:

double[] b = Array.ConvertAll(a, x =(double)x);

Marc
Sep 12 '08 #2
double[] b = Array.ConvertAll(a, x =(double)x);

btw, in C# 2.0 this is:

double[] b = Array.ConvertAll<decimal,double>(a, delegate (decimal x)
{return (double)x;});

Gotta love lambdas and the improved generic type inference ;-p

Marc
Sep 12 '08 #3
Marc,

In this case, there is no automatic conversion between decimal and
double - they are very different data types.
This is the point that interests me most.

http://msdn.microsoft.com/en-us/library/08h86h00.aspx , Decimal->Double
conversions are stated as being widening conversions although with
occasional information loss. If Decimal->Double conversions are widening
conversions, they are therefore automatic, no? Do you have any information
which could clear this up for me please?

--
Thank you,

Christopher Ireland

Sep 12 '08 #4
Marc,
double[] b = Array.ConvertAll<decimal,double>(a, delegate (decimal x)
{return (double)x;});

Gotta love lambdas and the improved generic type inference ;-p
Love 'em, and would even settle for anonymous methods, but the components we
write have to target .net 1.1 and the code is full enough of #ifs as it is
<g>!

--
Thank you,

Christopher Ireland

Sep 12 '08 #5
Well, the precisions and scales don't tie up neatly - and simply not all
decimal values can be represented accurately as double, so there is no
implicit conversion; you can check this with just:

decimal x = 23.45M;
double y = x; // error - needs explicit cast

The table on that MSDN page tells you that a conversion is possible: it
doesn't claim it is implicit. There is rarely an implicit conversion if
there is a risk of data loss.

Marc
Sep 12 '08 #6
Marc,
The table on that MSDN page tells you that a conversion is possible:
it doesn't claim it is implicit. There is rarely an implicit
conversion if there is a risk of data loss.
So am I to understand that the terms "implicit conversion" and "automatic
conversion" are synonymous? If so, then you have helped me satisfy my
curiosity, thank you!

--
Thank you,

Christopher Ireland

Sep 12 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.