Operator overloading +, therefore, it is sensitive to a call in a verified or uncontrolled context

UPDATE: I found an answer that I will post in a couple of days if no one does.


I am creating a numerical structure, so I overload the arithmetic operators. The following is an example structure representing a 4-bit unsigned integer:

public struct UInt4 { private readonly byte _value; private const byte MinValue = 0; private const byte MaxValue = 15; public UInt4(int value) { if (value < MinValue || value > MaxValue) throw new ArgumentOutOfRangeException("value"); _value = (byte) value; } public static UInt4 operator +(UInt4 a, UInt4 b) { return new UInt4((a._value + b._value) & MaxValue); } } 

The overloaded addition operator allows this code:

 var x = new UInt4(10); var y = new UInt4(11); var z = x + y; 

Here the calculation overflows, so the variable z has a value of 5 . I would also like to be able to do this, however:

 var x = new UInt4(10); var y = new UInt4(11); var z = checked ( x + y ); 

This pattern should throw an OverflowException. How can I achieve this?

I have already established that the checked context does not apply to the called methods, therefore, for example, it does not throw, regardless of whether it is called in the checked or unverified context:

 public static UInt4 operator +(UInt4 a, UInt4 b) { int i = int.MaxValue; //this should throw in a checked context, but when //the operator is used in a checked context, this statement //is nonetheless unchecked. byte b = (byte)i; return new UInt4((a._value + b._value) & MaxValue); } 

Is there a way to declare two addition operator overloads, one checked and the other not set? Alternatively, there is a way to determine the context of the caller at runtime (which seems unlikely, but I thought I was asking anyway), something like this:

 public static UInt4 operator +(UInt4 a, UInt4 b) { byte result = (byte)(a._value + b._value); if (result > MaxValue) if (ContextIsChecked()) throw new OverflowException(); else result &= MaxValue; return new UInt4(result); } private static bool ContextIsChecked() { throw new NotImplementedException("Please help."); } 
+7
source share
1 answer

According to MSDN, the keywords checked and unchecked apply only to integral types . Therefore, you cannot create your own types that can use verified and unverified keywords.

+2
source

All Articles