473,695 Members | 2,568 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Illegal typecast exception?

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)lis t[1];
float f3 = (float)(int)lis t[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
Nov 15 '05 #1
3 3235
Ray Mitchell <Ra************ ***@MeanOldTeac her.com> wrote:
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)lis t[1];
float f3 = (float)(int)lis t[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?


What's going on is that you're trying to unbox an int as a float, and
that won't work as you've already seen. What you can do is:

for (int i=0; i < list.Count; i++)
{
if (list[i] is float)
{
floatArray[i] = (float)list[i];
}
else if (list[i] is int)
{
floatArray[i] = (float)(int)lis t[i];
}
else
{
// Error handling
}
}

or you could use:

for (int i=0; i < list.Count; i++)}
{
floatArray[i] = Convert.ToSingl e(list[i]);
}

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #2
Ray Mitchell wrote:
float f1 = (float)(int)lis t[1];
float f3 = (float)(int)lis t[3];


Since you'll be casting to them all to float in the end, why not cast
them to float as you add them to the array?

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
(Pull the pin to reply)
Nov 15 '05 #3
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
InvalidCastExce ption 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************ ***@MeanOldTeac her.com>
Sender: "Ray Mitchell" <Ra************ ***@MeanOldTeac her.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: AcPJiIIINxNAWqb 9SV+CARJFr2p8Xg ==
X-MimeOLE: Produced By Microsoft MimeOLE V5.50.4910.0300
Newsgroups: microsoft.publi c.dotnet.langua ges.csharp
Path: cpmsftngxa07.ph x.gbl
Xref: cpmsftngxa07.ph x.gbl microsoft.publi c.dotnet.langua ges.csharp:2075 32
NNTP-Posting-Host: tk2msftngxa14.p hx.gbl 10.40.1.166
X-Tomcat-NG: microsoft.publi c.dotnet.langua ges.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)lis t[1];
float f3 = (float)(int)lis t[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

Nov 15 '05 #4

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

Similar topics

2
1891
by: rob | last post by:
Dear All, I am getting an error "Illegal cross-thread operation". I am not creating any threads. I know internally there are many threads running, though. Does that mean that no form can call a function from another form even if there is a parent-child relationship? Aren't controls like TreeView based on forms. If so then why can a form containing a TreeView call members of the TreeView? If you're interested here is my scenario:
1
2222
by: masood.iqbal | last post by:
I have a few questions regarding overloaded typecast operators and copy constructors that I would like an answer for. Thanks in advance. Masood (1) In some examples that I have seen pertaining to casting class A to class B, the implementation of the
12
2372
by: [Yosi] | last post by:
What I should do to return back the permissin I had in VS2003 , that allowd me to access public methode of one Class from other Thread. I have Class A(FORM) which create new thread (new class B), the new class thread get as parameter reference to his father( CLASS who mad it (classA)), The new thread need to call methodes from his father like myfathe.methode(), This worked in VS 2003 but now in VS 2005 Beta throw an exception : An...
0
933
by: Bruno van Dooren | last post by:
Hi, I am debugging a dll that is used in an application that calls all functions with C calling conventions, and cannot handle exceptions. Every 1-2 months there is a crash due to an unhandled exception, even though my dll does not throw any. I only know the function in whioch it is caused. I suspect that the cause is a 'new' that fails, or a delete of an illegal
12
7189
by: Wilfried Mestdagh | last post by:
Hi, Using P/Invoke I use PostMessage to send a message from one thread to another. I'm pretty sure this has already worked in dotnet. but I've upgraded version 2 few day ago. Now I have an illegal cross thread operation if posting a message. Is this a bug introduced in latest version of dotnet ? It is very legal to use postmessage because the message will execute in context of the thread the one was posted to. Same with...
6
13572
by: BlueTrin | last post by:
Hello I was adapting a C version of SolvOpt in C++ to use it within a virtual class. However I am stuck with the overriding of evaluation and gradiant functions. cStepCurveEvaluator.cpp cStepCurveEvaluator.cpp(14) : error C2296: '.*' : illegal, left operand
16
7502
by: DBC User | last post by:
Hi, I have a small XML file, I uploaded to a web page. I have the following code to convert the content I downloaded from web to xml and is giving "Illegal characters in path", but when I try to see the value in XML viewer (through add watch) and is showing the content correctly. Here is the code ... string b = wc.DownloadString(myurl);
3
4084
by: ryan.gilfether | last post by:
I have a problem that I have been fighting for a while and haven't found a good solution for. Forgive me, but my C++ is really rusty. I have a custom config file class: class ConfigFileValue { public: operator string(); // allow this class to be typecast into a string operator char*(); // allow this class to be typecast into a char*
1
2282
by: crusson | last post by:
(edited to add): this is in Visual Basic .net I am at a complete loss... I've been building a program on my machine, running it out of the developer with the f5 key and builidng it and running it off of my machine every once in a while. It works perfectly. I built it and sent it to my co worker's machine to test it out and it returns an "Illegal characters in path" error when the line: Dim objReaderOpen1 As New...
0
8647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8585
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9004
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8838
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7682
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5842
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4351
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2288
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1986
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.