[Mono-list] new color.cs for inclusion in CVS

Brian Crowell brian@fluggo.com
Thu, 7 Mar 2002 13:31:41 -0600


Here's a response to a question someone asked me about C# integer semantics:

> When should I use the unchecked option?

Use it when you don't want overflow checks and want to discard bits that
fall outside the destination type. This makes integer casts work more like C
casts. For example:

checked {
	byte me = (byte) 256;
}

...causes a compile-time error, because 256 is too big to fit in a byte.
But:

unchecked {
	byte sized = (byte) 256;
}

...results in the value zero, since the upper three bytes of the Int32 256
have been discarded.

For the left and right shift operators, this does not matter-- the
upper/lower bits are discarded as part of the operation, and overflow is
ignored. For other operators, you may want to do unchecked casting before
using them. (myint32 & 0xFF000000) goes through a lot of implicit casting
because the right operand is a UInt32, but unchecked { myint32 &
(int)0xFF000000; } does not. You'll want to read more about operators in
MSDN or the C# standard. For instance, did you know that the bitwise-AND
operator doesn't take byte, short, or ushort as operands? They all get
casted to Int32's first!

--Brian