Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing private member data

I'm trying to serialize an object to XML that has a number of properties, some of which are readonly.

public Guid Id { get; private set; } 

I have marked the class [Serializable] and I have implemented the ISerializable interface.

Below is the code I'm using to serialize my object.

public void SaveMyObject(MyObject obj) {     XmlSerializer serializer = new XmlSerializer(typeof(MyObject));     TextWriter tw = new StreamWriter(_location);     serializer.Serialize(tw, obj);     tw.Close(); } 

Unfortunately it falls over on the first line with this message.

InvalidOperationException was unhandled: Unable to generate a temporary class (result=1). error CS0200: Property or indexer 'MyObject.Id' cannot be assigned to -- it is read only

If I set the Id property to public it works fine. Can someone tell me if I'm doing something, or at least if its even possible?

like image 626
Jon Mitchell Avatar asked Apr 29 '09 14:04

Jon Mitchell


People also ask

Can private variables be serialized?

Yes, you can do it.

Can we serialize private variable in C#?

Hence, private variables are not serialized. You cannot serialize private members using XmlSerializer unless your class implements the interface IXmlSerializable.

What is serializing of data?

Data serialization is the process of converting an object into a stream of bytes to more easily save or transmit it. The reverse process—constructing a data structure or object from a series of bytes—is deserialization.

How do I prevent some data from getting serialized?

You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows. If possible, make an object that could contain security-sensitive data nonserializable. If the object must be serialized, apply the NonSerialized attribute to specific fields that store sensitive data.


1 Answers

You could use DataContractSerializer (but note you can't use xml attributes - only xml elements):

using System; using System.Runtime.Serialization; using System.Xml; [DataContract] class MyObject {     public MyObject(Guid id) { this.id = id; }     [DataMember(Name="Id")]     private Guid id;     public Guid Id { get {return id;}} } static class Program {     static void Main() {         var ser = new DataContractSerializer(typeof(MyObject));         var obj = new MyObject(Guid.NewGuid());         using(XmlWriter xw = XmlWriter.Create(Console.Out)) {             ser.WriteObject(xw, obj);         }     } } 

Alternatively, you can implement IXmlSerializable and do everything yourself - but this works with XmlSerializer, at least.

like image 140
Marc Gravell Avatar answered Sep 20 '22 17:09

Marc Gravell