Home All Groups Group Topic Archive Search About

HOWTO: Convert "Type" to a byte array and Back

Author
6 Apr 2006 8:32 PM
Scott
Hi All,

I am trying to convert an ArrayList (that can contain an array of any type)
to a byte array.
Using the BinaryWriter and BinaryReader is not helpful, for example since
the ArrayList can contain an array of doubles it is necessary to cast the
following:
    binWriter.Write((double)dblArrayList[0]);
However since the ArrayList can be of any type it is not possible (or is it)
to perform a cast at run time.

So what is desired is to have a mechanism that will perform conversions of
an ArrayList (of any type) to a byte array and to do the reverse, convert a
byte array back to an array list.
Note that the type is known by saving the type in a struct as a string I.E.:
"System.Double" along with the ArrayList.

Thanks for any help in advance.

Scott

Author
6 Apr 2006 8:37 PM
Mattias Sjögren
Scott,

>So what is desired is to have a mechanism that will perform conversions of
>an ArrayList (of any type) to a byte array and to do the reverse, convert a
>byte array back to an array list.

Have you tried using the framework's serialization support?


Mattias

--
Mattias Sjögren [C# MVP]  mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Author
7 Apr 2006 8:18 PM
Scott
Mattias,

I was able to use the BinaryFormatter class along with the MemoryStream and
BinaryWriter classes to accomplish this task
The only casting necessary was when deserializing the ArrayList class back.

Thanks!
Scott

Show quote
"Mattias Sjögren" wrote:

> Have you tried using the framework's serialization support?
>
> Mattias

AddThis Social Bookmark Button