Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interesting little SEHexception problem with struct, C# [duplicate]

Tags:

c#

.net

puzzle

Can anyone explain why the below code throws an error. It can easily be fixed by either casting the -1 value to a decimal (-1M), by changing the operator overload to accept an int or by not using a nullable object.

I have noticed the error doesnt get thrown in VS2010 only VS2008.

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

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;
    }
}
like image 795
CeejeeB Avatar asked Nov 25 '22 14:11

CeejeeB


2 Answers

No repro with the given code snippet. The code you used however strongly resembles the kind of code that falls over on an old bug in the C# compiler. The details are in this thread, Eric Lippert is already aware of it.

like image 120
Hans Passant Avatar answered Nov 28 '22 04:11

Hans Passant


It works fine (on my machine) in both VS 2008 and VS 2010. BTW, your implementation of * is incorrect. It should be:

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

Probably you've meant operator *(MyObject value1, decimal value2) which is really failing.

like image 33
Snowbear Avatar answered Nov 28 '22 03:11

Snowbear