Solved

Casting woes from System.Single directly to System.Double

Posted on 2004-10-14
2
230 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
  • 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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

786 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