9.10. Casting for value types

Like Java, casting in C# can be implicit as well as explicit. Widening casts [8] can be performed implicitly, while narrowing casts have to be stated explicitly.

[8] A widening cast is a cast from a simple type of lower range to one of higher range. Examples include casting a short to an int, an int to a long, a float to a double. A narrowing cast is the opposite. Casting a long to an int is a narrowing cast.

Figure 9.4 shows the allowed implicit casts in C#. Unlike Java, which has only eight primitive types, the C# picture is more complex with four more types.

Figure 9.4. Direction of arrows shows legal implicit casting. The shaded boxes are integral simple types.

Figure 9.4 is very useful in determining whether ...

Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.