Casting woes from System.Single directly to System.Double
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?
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?
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
}
Not sure what exactly is the issue without looking at the definition of myReader. Could you post the exception thrown?