Hi,
You have boxed a value type. When unboxing the type the following rule is
applied
"For an unboxing conversion to a given value type to succeed at run time,
the value of the source argument must be a reference to an object that was
previously created by boxing a value of that value type. If the source
argument is null or a reference to an incompatible object, an
InvalidCastException is thrown."
According to the rule your unboxing "int" type to a "float" and they are
not the same, so the exception is thrown. For more details read read about
Boxing/Unboxing.
The following works for me...
for (i = 0; i < list.Count; ++i)
floatArray[i] = System.Convert.ToSingle(list[i]);
Hope that helps.
_Rakesh
--------------------
Content-Class: urn:content-classes:message
From: "Ray Mitchell" <Ra***************@MeanOldTeacher.com>
Sender: "Ray Mitchell" <Ra***************@MeanOldTeacher.com>
Subject: Illegal typecast exception?
Date: Tue, 23 Dec 2003 11:11:03 -0800
Lines: 35
Message-ID: <00****************************@phx.gbl>
MIME-Version: 1.0
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
X-Newsreader: Microsoft CDO for Windows 2000
Thread-Index: AcPJiIIINxNAWqb9SV+CARJFr2p8Xg==
X-MimeOLE: Produced By Microsoft MimeOLE V5.50.4910.0300
Newsgroups: microsoft.public.dotnet.languages.csharp
Path: cpmsftngxa07.phx.gbl
Xref: cpmsftngxa07.phx.gbl microsoft.public.dotnet.languages.csharp:207532
NNTP-Posting-Host: tk2msftngxa14.phx.gbl 10.40.1.166
X-Tomcat-NG: microsoft.public.dotnet.languages.csharp
Hello,
I have an array list whose elements are the following
types:
float
int
float
int
...etc.
I have the following code dealing with the elements:
float f0 = (float)list[0];
float f1 = (float)list[1];
float f2 = (float)list[2];
float f3 = (float)list[3];
Although the code compiles fine, I get a "Specified cast
is not valid." runtime exception on f1 and f3. I can fix
it by doing the following:
float f1 = (float)(int)list[1];
float f3 = (float)(int)list[3];
However, that's rediculous since in reality my code is a
loop that merely does something like:
for (i = 0; i < list.Count; ++i)
floatArray[i] = (float)list[i];
What's going on?
Thanks,
Ray Mitchell
Rakesh, EFT.
This posting is provided "AS IS" with no warranties, and confers no rights.
Use of included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm