How does the C# compiler guarantee conversion success?

Viewed 113

I am learning with C# 7.0 in a Nutshell 7th edition. There is a portion of the text that I could not understand (page 24 & 25)

"Implicit conversions are allowed when both of the following are true:

1) The compiler can guarantee they will always succeed.

2) No information is lost in conversion. (A minor caveat is that very large long values lose some precision when converted to double)

Conversely, explicit conversions are required when one of the following is true:

1)The compiler cannot guarantee they will always succeed.

2)Information may be lost during conversion."

If the compiler can determine that a >conversion will always fail, both kinds of conversion are prohibited"

Can you give me examples for when the compiler cannot guarantee conversion ?

3 Answers

The answers so far focus on value types.

For reference types there are base-class, derived class and interface conversions.

class A  { }       // base class
class B : A { }    // B is-an A 
class C : A { }    // C is-an A 

B b = new B(); // instance of B 
A a = b;       // ok, conversion to base class can't fail because B is an A
C c = (C) a;   // but conversion to derived could fail, a could be a B 

Implicit conversions exist for data type upcasts, like short to int, or int to long. Another example is int to float or double. Such data types can always cast to their larger counterpart data types.

The other way around is not true: a double can't (always) be converted to an int. A long doesn't always fit in a int or short.

An example of when the compiler can't guarantee conversion would be if you are making assumptions about types at run time. A very loose example might be this

public int Add(object a, object b)
{
    return ((int)a) + ((int)b);
}

Here you are working on the assumption that you will be passed an int at runtime, for whatever reason you've lost the type safety and you are working with an object. The compiler does not and cannot know this at compile time, hence why you need the explicit cast.

This is an extreme example but hopefully it clears it up a bit for you

Related