The task is to write a class with methods that will serialize, deserialize any object into an array of bytes and vice versa. I wrote a serialization (not sure if this is correct)

static byte[] Serialize<T>(T obj) where T : class { if (obj == null) { return null; } using (var stream = new MemoryStream()) { DataContractSerializer ser = new DataContractSerializer(typeof(T)); ser.WriteObject(stream, obj); return stream.ToArray(); } } 

An example is, for example, here , but they use an xml file, and I need it without it. How to write serialization / deserialization without a file? Will I get object bytes from a stream?

  • So it will work, yes. Get back the data quite well. However, the DataContractSerializer serializes to xml, which is then written to the stream. If you need an array of bytes, it is probably best to use binary serialization. For example, BinaryFormatter . - Alexander Petrov
  • Please pay attention to the tag UWP. BinaryFormatter is not in .NetCore. - Sanych Goilo
  • If you are given an exhaustive answer, mark it as correct (tick the selected answer). - andreycha

2 answers 2

 public static byte[] Serialize<T>(T obj) where T : class { using (var stream = new MemoryStream()) { DataContractSerializer serializer = new DataContractSerializer(typeof(T)); serializer.WriteObject(stream, obj); stream.Position = 0; return stream.ToArray(); } } public static T Deserialize<T>(byte[] data) where T : class { using (var stream = new MemoryStream()) { stream.Write(data, 0, data.Length); stream.Position = 0; DataContractSerializer deserializer = new DataContractSerializer(typeof(T)); return deserializer.ReadObject(stream) as T; } } 
  • The methods turned out asymmetrical. It is necessary to use typeof(T) in the first one, and not obj.GetType() . - Pavel Mayorov
  • By the way, why write an array into a stream if you can wrap the stream over an array? .. - Pavel Mayorov
  • Well, for the MemoryStream using not required - because it does not contain resources. - Pavel Mayorov

Here is a simpler option:

 public static byte[] Serialize<T>(T obj) where T : class { var stream = new MemoryStream(); var serializer = new DataContractSerializer(typeof(T)); serializer.WriteObject(stream, obj); return stream.ToArray(); } public static T Deserialize<T>(byte[] data) where T : class { var stream = new MemoryStream(data); var deserializer = new DataContractSerializer(typeof(T)); return deserializer.ReadObject(stream) as T; }