Is casting the same thing as converting?

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

Leave a Comment