Spintz

I have a class, that has various members, that add up to 248 bytes of data. I receive this data from a TCP socket and have it in byte[] form. I want to simply take the data I got over the socket, and copy the whole slot of memory, into the class. Not a structure, a class.

Is this possible



Re: .NET Framework Networking and Communication Marshalling Classes

PhilipRieck

You're basically deserializing data from a byte array into an object instance, correct

You could look into using the serialization framwork and do custom binary serialization if you wish.

Or, what is probably the simplest solution is just provide a constructor to your class that takes a byte[] array and reads the data from it to initialize itself.

Code Snippet

public class SomeClass

{

private string m_StringProp;

public string StringProp

{

get{ return m_StringProp;}

}

public SomeClass(byte[] data)

{

//not-shown: validate the data argument first!

//say the first 10 bytes are StringProp

byte[10] someBytes;

Array.Copy(data, 0, someBytes, 0, 10);

//use whatever encoding the string bytes are in. or use the String(byte[]) constructor if applicable

System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
m_StringProp = enc.GetString(someBytes);

//Get other properties out

}

}