C# – How to Get the length of a TypeCode


I'm sure this is an easy question, but I don't have an answer for. Here's the senario and the question.

I have an array that was stored using in a particular format. The format contains a Header record with muntiple detail records following it. The header of the record tells me what TypeCode was used to store the data, for instance Int32.

I have a routine that takes a byte[] array and converts the byte data back to it's proper format in C#. This routine needs the proper number of bytes to make the conversion successful.

Q. So how can I get the length of bytes from the given TypeCode for passing to the Convert function without having to hardcode the length for every type?

Best Solution

Given that TypeCode is just an enumeration of a fixed set of values, you could easily hard-code a dictionary of them, e.g.

private static readonly Dictionary<TypeCode,int> TypeCodeLength =
    new Dictionary<TypeCode,int> {
    { TypeCode.Int32, 4 },
    { TypeCode.Int64, 8 },
    { TypeCode.Char, 2 },
    // etc

(An equivalent solution would be to use a switch/case statement - they really are equivalent if you're just including values.)

Some, like string and object will be variable though - and others will depend on how you're encoding things like DateTime.

Unless this is using a standard conversion, nothing in the framework is going to be able to give you the lengths. I know hard-coding is generally frowned upon, but in this case it's only in one place and is going to be the simplest option.