"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in message
news:%2****************@TK2MSFTNGP03.phx.gbl...
It should be noted that there is nothing that is particularly special about the
GenercBinaryFormatter. If anything, they prevent the cast that is necessary when calling
Deserialize on IFormatter implementations. Other than that, it doesn't do anything special for
Generic instances.
Also, the OP should note that there is no way to determine the size, in bytes, of an object in
memory without having a hook in the CLR. The serialized version of the instance is not
representative of what is stored in the byte array.
Sizeof will only work in unsafe code and only on value types, so it won't work for all types,
T.
To the OP, what exactly are you trying to do?
I'm trying to generate a binary blob from an array.
I have some array of values as a source and I want to convert
it to an array of bytes as a destination. See the following code
class Blob<T>
{
private int length_;
private T[] data_;
public Blob(int size)
{
length_ = 0;
data_ = new T[size];
}
public void Add(T value)
{
if (length_ >= data_.Length)
throw new StackOverflowException();
data_[length_++] = value;
}
public byte[] GetBytes()
{
if (length_ == 0)
return null;
int sizeOfElement = Marshal.SizeOf(data_[0]);
byte[] buffer = new byte[length_ * sizeOfElement];
for (int i = 0; i < length_; i++)
{
// the following row cause a compilation error
Array.Copy(BitConverter.GetBytes(data_[i]), 0, buffer, i * sizeOfElement,
sizeOfElement);
}
return buffer;
}
}