Solved

Casting woes from System.Single directly to System.Double

Posted on 2004-10-14
2
232 Views
Last Modified: 2010-04-15
I am reading from a SQL table whith a row "open" of type "float" (which C# / .NET reads as a System.Single value).

Here is the code:
1. Console.WriteLine("Value: {0}, data type={1}", myReader["open"], myReader["open"].GetType());
2. float f = (float)(myReader["open"]);
3. d = (double)f;
4. d = (double)(myReader["open"]);

1. prints: Value: 24.02, data type=System.Single
2. No problem (f=24.02)
3. No problem (d=24.02)
4. Exception - invalid cast ...

Why? How is statement 4 different than 2 & 3 combined? Does C# have trouble doing the conversion directly, and if so, what would be an elegant and robust way to do it?

Thanks,
Patrick
0
Comment
Question by:patrickq
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
2 Comments
 
LVL 3

Expert Comment

by:aacool
ID: 12322363
Please see my code below - this works fine - no exceptions are thrown.
   try
   {
         System.Single single = 5.3F;
         float f= (float)single;
         double d1 = (double)f;
         double d2 = (double)single; // no exception thrown.
   }
   catch(Exception ex)
   {
      MessageBox.Show(ex.Message+ex.StackTrace);
   }



Not sure what exactly is the issue without looking at the definition of myReader. Could you post the exception thrown?
0
 
LVL 3

Accepted Solution

by:
aacool earned 50 total points
ID: 12352370
Did this work out for you?
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question