Serialize and deserialize class to Byte[] on IOS

How can i serialize and deserialize a class to a Byte Array on IOS.

I mean that I write something like

byte[] SerializeBytes = SerializeObject<ClassToSerialiteIn> (InstanceOfTheClassToSerialize);


ClassToSerialiteIn someClass = DeserializeObject<ClassToSerialiteIn> (SerializedBytes);

Not sure from your question if you actually want a byte array or a string, but here is a solution for a byte array. The answer should be applicable to Mono as well:

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

// ...

object obj = new object ();
byte[] bytes;
IFormatter formatter = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream())
	formatter.Serialize(stream, obj);
	bytes = stream.ToArray();

Note that you probably shouldn’t be using byte arrays for persistence of classes, since it won’t be compatible with any changes to the class or to the Mono .NET framework, and won’t be portable to any other platforms. I’d only use it if you’re transporting data between the exact same version of the same application. Otherwise you might want to look into JSON, XML, or even a serverless database.

I tested the script of @alfalfasprout. Yeah! its working. Now what is the sample used of this?
First, for example: you want to send an entire class with variables for sync player prefab on the current device to other device which have the clone of the said playerPrefab in Multiplayer Implementation. Just sharing hopefully this help.