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;
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With