Search code examples
c#arraysvisual-studio-2013

Why do both Convert.ToInt32(Byte) and Convert.ToInt32(Byte[]) compile, but Convert.ToInt32(byte[]) throw a runtime exception?


I get an invalidcastexception whenever I use Convert.ToInt32(byte[]) and was wondering if I was doing something wrong, of if this is something that is well known.

Why is it that a byte[] doesn't throw a compiler error when there is no overload that supports a byte[] in this method?


Solution

  • You can't convert a byte[] to an int using Convert.ToInt32. You need to use a BitConverter.

    The difference is that the BitConverter is built to do exactly what you're trying to do: take an array of bytes and convert them into their integral representation. Convert.Int32 is meant for converting anything that's already an integer, or can be converted to an integer using the IConvertible interface.

    Convert can be used only for types that implement the IConvertible interface.