Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Convert object type to byte[]?

Status
Not open for further replies.

cjtaylor

Programmer
Aug 12, 2001
69
US
Hey,

How the heck do you convert an object type to a byte array. I have tried all kinds of ways but have not succeeded. Someone please show me how?

Thanks
 
It seems like you want to convert from object[] to byte[].
I don't know a direct conversion but you could try one of the following 2 workarounds:

1. Copy and convert each array member:
Code:
object[] o = new object[1];
byte[] b = new byte[o.Length];
for (int i = 0; i < o.Length; i++)
    b[i] = (byte)o[i];

OR

2. Convert to a collection and back to an array:
Code:
// using System.Collections;
object[] o = new object[1];
byte[] b = (byte[]) new ArrayList(o).ToArray(typeof(byte));

Neither of these workarounds is really fast in therms of runtime efficiency, so there may be a better way to do it.

Hope this helps,
aperion
 
Is this for serialization?

Chip H.


If you want to get the best response to a question, please check out FAQ222-2244 first
 
I can't use serialization because the underlying object is a System.__ComObject and when I try to serialize it, the compiler throws an error saying that the object is not maked serializable. So, I am trying to look for another approach to saving this object.
 
I think you can try the followings:
Retrieve the Type object of the object e.g. Type tp= o.GetType();
Now use tp.FindMembers() to find out the nonstatic fields.
If a field is a value type, then retrive MemberInfo about it and copy bit-by-bit this field in the output array.
If the field is a reference type, you decide to copy the reference only to the output array or the referred object.
-obislavu-
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top