Question

C++: DWORD dwState = (DWORD)-1;

Here there is no issues.

C#: uint state = -1;

Here, uint or UInt32 which is considered to be the equivalent of DWORD cannot have a negative value and it throws below exception.

Value was either too large or too small for a UInt32

I have a code which reads this value (which is stored in DB) both from cpp and c# programs. Cpp marks invalid state as -1. Hence I'm unable to read it from C# front with uint type. I cannot change this type in c++ program. Apart from -1, cpp may write any value between 0-65536 for variable.

How can I handle it from C# front!?

Was it helpful?

Solution

How can I handle it from C# front!?

You can use the unchecked operator for the constant assignment:

uint state = unchecked((uint) -1);

From the C# spec section 7.6.12:

The checked and unchecked operators are used to control the overflow checking context for integral-type arithmetic operators and conversions.

...

For constant expressions (expressions that can be fully evaluated at compile time), the default overflow checking context is always checked. Unless a constant expression is explicitly placed in an unchecked context, overflows that occur during the compile-time evaluation of the expression always cause compile-time errors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top