Implicit Versus Explicit Conversions

There are two types of conversions in C#, implicit and explicit. Implicit conversions happen automatically, without any special syntax or casting. For example, converting an int to a long can occur as a normal assignment operation as follows:

int  myInt  = 5;
long myLong = myInt;

This conversion occurs without problem because of two simple principles. First, the long is a 64-bit value and the int is a 32-bit value. The int can fit into the long with no problem. Second, no errors will occur. The semantics of an int value don't change when it's put into a long variable. It still represents the same thing—a whole number.

On the other hand, an explicit conversion is required when the same principles don't lead ...

Get C# Unleashed 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.