An interesting little SEHexception problem with struct, C #

Possible duplicate:
SEHException.net Conundrum

A colleague pointed to this interesting exception, which has begun to appear recently. (note that this is just a toy version for real code)

using System;

namespace ConsoleApplication19
{
    class Program
    {
         static void Main(string[] args)
        {
            var o1 = new MyObject?(new MyObject(2.34M));
            o1 *= -1; //This line throws SEHException
         }
    }

    public struct MyObject
    {
        public MyObject(Decimal myValue)
        {
            this.myValue = myValue;
        }

        private Decimal myValue;

        public static MyObject operator *(MyObject value1, Decimal value2)
        {
            value1.myValue *= value2;
            return value1;
        }
   }
}

The marked line throws an SEHException "External component" exception. Obviously, the error is that -1 on this line should be -1M, so the arg argument is of the correct type, this change stops the generated exception. Interestingly, by making a minor “cosmetic” change to the code, the exception is no longer thrown.

// If you invert the order of the operands to MyObject.*() , and expand out the *= in main,
// the thing runs without throwing the exception :s

// If you step through, the value of myValue is correctly ‘invalid decimal value’ after * by -1.

using System;

namespace ConsoleApplication19
{
    class Program
    {
        static void Main(string[] args)
        {
            var o1 = (MyObject?)new MyObject(2.34M);
            o1 = -1 * o1 ;
        }
    }

    public struct MyObject
    {
        private Decimal myValue;

        public MyObject(Decimal myValue)
        {
            this.myValue = myValue;
        }

        public static MyObject operator *(Decimal value2,  MyObject value1)
        {
            value1.myValue *= value2;
            return value1;
    }
    }
}

Note that everything we did inverts the order of the arguments to * defined for MyObject, and extends * = to be more explicit. I was thinking maybe the fact that the values ​​hit the stack in a different order avoids the exception? But I'm pretty ignorant.

Just to clarify: I don’t need a solution to stop the generated exception, we have it, I’m more interested in why the exception occurs, and why making minor cosmetic changes to the code fixes the "problem."

prompt

: it was also reported that the exception was not selected in visual studio 2010, only in 2008.

Any help is appreciated :)

+5
source share

All Articles