Why does IntPtr.ToInt32 throw an OverflowException in 64-bit mode, but Explicit (IntPtr to Int32) does not

The statement description on MSDN has a remark:

An exception is thrown only if the value value requires more bits than the current platform supports.

while ToInt32 description is wrong, I suppose the name is not entirely correct (for brevity),

a more correct question would be: "Why IntPtr.ToInt32 throws OverflowException in 64-bit mode for values ​​that fit in Int32 and Explicit (IntPtr in Int32), not"

In a decompiled IntPtr ToInt32 and the operator looks very similar:

 public static explicit operator int(IntPtr value) { return (int) value.m_value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public unsafe int ToInt32() { return (int) this.m_value; } 

I wonder what makes ToInt32 exception, is this an unsafe keyword?

+4
source share
1 answer

Your disassembler cannot do the right job here, mscorlib.dll is special. This is not an AnyCPU assembly; Microsoft builds and ships different versions based on the processor architecture. I recommend that you use Reference Source , you will get the source code. Which looks like this:

  [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public unsafe int ToInt32() { #if WIN32 return (int)m_value; #else long l = (long)m_value; return checked((int)l); #endif } 

This is the checked keyword, which provides an OverflowException.

+8
source

All Articles