Implicit Conversion
- The most common operation that results in a conversion is casting.
- Implicit conversion happens when there is no loss of precision and there will be no fundamental change in the value of the target type.
- The compiler can prove that this is safe just from static analysis (List<int> is always an IList<int>).
int intNumber = 31416;
long longNumber = intNumber;
List<int> l = new List<int>();
IList<int> il = l;
- In an implicit primitive conversion, it is generally assumed that there is a safe, non-risky, non-lossy conversion:
int i = 1;
float f = i;
- There is no valid cast from a numeric type to a Boolean type in C#, although this is common in many other languages.
- The reason is to avoid any ambiguity, such as whether –1 corresponds to true or false.
- More importantly, this also reduces the chance of using the assignment operator in place of the equality operator.
- E.g. avoiding
if (x = 42) {...}
when if (x == 42) {...}
was intended.
Explicit Conversion with “Cast Operator”
- Explicit cast occurs for any conversion that could result in a loss of magnitude or an exception may occur.
- Cast operator functions by specifying the target type. Indeed, you acknowledge that the cast may result in a loss of precision/data, or an exception.
long longNumber = Int32.MaxValue;
longNumber += 1;
int intNumber = (int) longNumber;
- During the explicit cast, you may tell the compiler that your cast is safe.
- Although the first cast is possible in the following code, the compiler won't accept that all
IList<int>
are List<int>
- so we must tell it to let it by.
List<int> l = new List<int>();
IList<int> il = l; // Implicit Cast
List<int> l2 = (List<int>)il; // Explicit Cast
- With CLR operators, you'd have to look at the documentation. It could be a reference cast, or it could be anything.
- It may follow similar rules to primitive conversions (for example: decimal), or it could do anything randomly:
XNamespace ns = "<http://abc/def>"; // Implicit cast with no data lose.
XAttribute attrib = GetAttrib();
// Explicit case. (Extracts text from attrib value and parses to an int).
int i = (int) attrib;
Checked and Unchecked Conversions
- If the target data type is too small to contain the assigned data, we can choose whether truncate or overflow the data.