using generics to serialize primitives.
- From: Brian <Brian@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Tue, 20 May 2008 07:21:00 -0700
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
.
- Follow-Ups:
- Re: using generics to serialize primitives.
- From: colin
- Re: using generics to serialize primitives.
- From: qglyirnyfgfo
- Re: using generics to serialize primitives.
- From: Marc Gravell
- Re: using generics to serialize primitives.
- Prev by Date: Re: How to change directories using FtpWebRequest?
- Next by Date: Re: adding attribute to a xml element
- Previous by thread: way to capture how much RAM the assembly is using?
- Next by thread: Re: using generics to serialize primitives.
- Index(es):
Relevant Pages
|