Is casting the same thing as converting?

Solution 1:

Absolutely not!

Convert tries to get you an Int32 via "any means possible". Cast does nothing of the sort. With cast you are telling the compiler to treat the object as Int, without conversion.

You should always use cast when you know (by design) that the object is an Int32 or another class that has an casting operator to Int32 (like float, for example).

Convert should be used with String, or with other classes.

Try this

static void Main(string[] args)
{
    long l = long.MaxValue;

    Console.WriteLine(l);

    byte b = (byte) l;

    Console.WriteLine(b);

    b = Convert.ToByte(l);

    Console.WriteLine(b);

}

Result:

9223372036854775807

255

Unhandled Exception:

System.OverflowException: Value is greater than Byte.MaxValue or less than Byte.MinValue at System.Convert.ToByte (Int64 value) [0x00000] at Test.Main (System.String[] args) [0x00019] in /home/marco/develop/test/Exceptions.cs:15

Solution 2:

The simple answer is: it depends.

For value types, casting will involve genuinely converting it to a different type. For instance:

float f = 1.5f;
int i = (int) f; // Conversion

When the casting expression unboxes, the result (assuming it works) is usually just a copy of what was in the box, with the same type. There are exceptions, however - you can unbox from a boxed int to an enum (with an underlying type of int) and vice versa; likewise you can unbox from a boxed int to a Nullable<int>.

When the casting expression is from one reference type to another and no user-defined conversion is involved, there's no conversion as far as the object itself is concerned - only the type of the reference "changes" - and that's really only the way that the value is regarded, rather than the reference itself (which will be the same bits as before). For example:

object o = "hello";
string x = (string) o; // No data is "converted"; x and o refer to the same object

When user-defined conversions get involved, this usually entails returning a different object/value. For example, you could define a conversion to string for your own type - and this would certainly not be the same data as your own object. (It might be an existing string referred to from your object already, of course.) In my experience user-defined conversions usually exist between value types rather than reference types, so this is rarely an issue.

All of these count as conversions in terms of the specification - but they don't all count as converting an object into an object of a different type. I suspect this is a case of Jesse Liberty being loose with terminology - I've noticed that in Programming C# 3.0, which I've just been reading.

Does that cover everything?