Question

I'm getting some unexpected behaviour from a TypeCast conversion in C#..

When trying to convert..

float f = 123124334234234.34F;

into an Integer as follows:

int i = (int)f;

I'm getting an Exception thrown. According to MSDN "In general, implicit conversion operators should never throw exceptions and never lose information so that they can be used safely without the programmer's awareness.".

Also, according to this guy at the 7:54 mark in the video, he states and shows an example where a typecast operator is used for a conversion does not throw an Exception.

video link: http://www.youtube.com/watch?v=IcDaNmGDMoM&index=8&list=PLAC325451207E3105

So why an I getting an OverflowException when I run the above code?

Était-ce utile?

La solution 2

By default, SharpDevelop enables the "Check for arithmetic overflow/underflow" flag, which Visual Studio has disabled by default.

You can disable it in the project properties:

enter image description here

Similarly, if anyone stumbles on this post and is using Visual Studio:

enter image description here

Autres conseils

I think you may have the /checked+ compiler flag set. With that switched on, arithmetic operations that would normally overflow instead throw exceptions at run-time.

If an integer arithmetic statement that is not in the scope of a checked or unchecked keyword results in a value outside the range of the data type, and /checked+ (/checked) is used in the compilation, that statement causes an exception at run time.

With the following code:

float f = 123124334234234.34F;
int i = (int)f;

With the setting turned off, it overflows to a negative number normally. With the flag switched on, it throws the overflow exception instead.

EDIT: That said, I don't know how to change that flag in SharpDevelop. Instructions for Visual Studio are included in the linked page above; perhaps they are similar for SharpDevelop.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top