how can i translate a object of my defined class to byte[]

  • Thread starter Thread starter lqs
  • Start date Start date
L

lqs

hi£¡
i am writing a program using Socket . There is a class , for example:

public class Student
{
public int nAge;
public string strFirstName;
public string strLastName;
}

Student s=new Student();
s.nAge=22;
s.strFirstName="victor";
s.strLastName="Smith";


then ,before i send the 's' by send() function,how do i translate this
object (i mean 's') to byte[]?
Because the parameter of this send() is byte[].


Thank you for your help!
 
You could serialize your object into a memory stream:

byte[] bytes;

using (MemoryStream stream = new MemoryStream())

{

BinaryFormatter formatter = new BinaryFormatter();

formatter.Serialize(stream, s);

bytes = stream.GetBuffer();

Console.WriteLine(BitConverter.ToString(bytes));

// Get the object back

stream.Position = 0;

Student clone = (Student)formatter.Deserialize(stream);

}

For this code to work you need to apply SerializableAttribute to your
Student class:

[Serializable]
public class Student
....

HTH,
Alexander Shirshov
 
Back
Top