c# - Function saved through Binary, then XML, then loaded

I’m trying to do a weird thing here.

myClass myObject= new myClass();
MemoryStream memStream = new MemoryStream ();
Binary.Serialize (memStream,myObject);
Data=memStream.GetBuffer();

This is how I saved a object, and it worked… But then I tried to load it and I don’t know how.

MemoryStream memStream = new MemoryStream ();
memStream.Read(Data,0,Data.Length);
myClass OBJ=Binary.Deserialize(memStream) as myClass;

This is what I came to and it doesn’t work. Can anybody help?

It makes not much sense to “read” from a newly created MemoryStream. I think you want to use the Write method. Keep in mind when writing the stream pointer is updated. so you would need to reset it vefore you use the stream in the Deserialize method.

Can you include a bit more information about your actual types here? What’s the type of “Data”? Is it the same “Data” in your serialize and deserialize code? a byte array?

If Data is a byte array you should simply use the MemoryStream constructor that takes a byte array.

myClass OBJ;
using(MemoryStream memStream = new MemoryStream (Data))
{
    OBJ = (myClass)Binary.Deserialize(memStream);
}

Note that classnames should be “UpperCamelCase”, in your case “MyClass”. Also when using streams / filestreams and things like that it’s best practise to wrap then in “using” statements. That ensures that Dispose() is called once the using block is left. This is important for objects that might hold native or unsafe data (like OS resources / file handles / …)