using generics to serialize primitives.

Tech-Archive recommends: Fix windows errors by optimizing your registry



What is the easiest way to convert primitives to a byte array? I tried the
BinaryFormatter serialization but it serializes objects so when I serialized
an and int it took 54 bytes instead of 4. I tried something like the
following but it won't compile (I admit I use generics a lot but haven't
written many so this may be way off):

class X<T>
{
public byte[] ToByteArray(T val)
{
BinaryWriter bw = new BinaryWriter(new MemoryStream());
bw.Write(val);
BinaryReader br = new BinaryReader(bw.BaseStream);
br.BaseStream.Position = 0;
return br.ReadBytes((int)br.BaseStream.Length);
}
}

I don't want to have an overloaded method for every primitive type. Is there
an easy way to do this...or have the overloads already been written to do
this and I am just missing it? It seems like a pretty basic task that should
be there somewhere already.

thanks
.



Relevant Pages

  • Re: A serialization problem
    ... The serialization seems to work OK (at least, ... > FileStream fileStream = new ... > BinaryFormatter formatter = new BinaryFormatter; ... > Gossip TeleCard ö<ÂÿÿÿÐÿÿÿ?GG05 - Oz Experience Phonecard ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Newbie Q: Serialization and Me
    ... Dim bf As BinaryFormatter = New BinaryFormatter ... I have 2 objects and I want to make a deep copy of one into the ... Target as T) as Integer 'use serialization to make a deep ...
    (microsoft.public.dotnet.languages.vb)
  • A serialization problem
    ... The serialization seems to work OK (at least, ... public class PersistantSettings ... BinaryFormatter formatter = new BinaryFormatter; ... Gossip TeleCard ö<ÂÿÿÿÐÿÿÿ?GG05 - Oz Experience Phonecard ...
    (microsoft.public.dotnet.languages.csharp)
  • RE: Challenge? [De-]Serialise a class derived from DataTable.
    ... Have you tried binary serialization? ... structures) when i deserialize them i get them back in the original ... Dim m As New MemoryStream ... Dim b As New BinaryFormatter() ...
    (microsoft.public.dotnet.languages.vb)
  • Question about data size when using serialized writing using BinaryFormatter
    ... I am writing a structure marked as serializable to a data file using the ... The structure does not inherit from any other types. ... BinaryFormatter, the resulting file size is much more. ... with the storage during serialization? ...
    (microsoft.public.dotnet.framework.clr)