views:

70

answers:

2

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?

A: 

According to How to create Type from TypeCode..., you can't (without a exhaustive switch). Of course the other direction (Type->TypeCode) is trivial.

Matthew Flaschen
+2  A: 

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.

Jon Skeet
I must have misunderstood the question. :) For this implementation, it seems like you could use a model like a BSTR where the first four bytes of the array represent the length of the type or some such convention like that.
JP Alioto
Of course, just like the switch, this breaks if a new type is introduced.
Matthew Flaschen
Introducing a new member to an enum is *always* a breaking change. I don't expect the TypeCode enum to change any time soon... Microsoft aren't likely to want to break the code of every developer who is switching on it.
Jon Skeet
Thanks for the interesting solution!
Rick