Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialise an instance of a class containing private members?

I want to serialise an instance of a class to IsolatedStorage.I have tried SharpSerialiser ,but it can serialise only public properties.But my class has private members(with no properties) ,static members etc.In DataContractSerializer also i think we can serialise only public members.So is there any way to serialise it?

Thanks and Regards vaysage

like image 714
Vaysage Avatar asked May 05 '11 05:05

Vaysage


People also ask

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.

Are private fields serialized?

So yes, it will serialize private fields if you mark them with [SerializeField] attribute.

How do you make a third party class serializable?

I'd suggest to create a data transfer object that contains the data that you want to provide through your service. Instead of making the ThirdPartyClass part of MyClass, use the new DTO and map the data of the ThirdPartyClass to the DTO before returning it from the Service.


2 Answers

Silverlight has a harsher reflection security model, and does not support the usual tricks used to bypass this. AFAIK, you are limited to public members.

You could of course make the object self-serializing, perhaps via a custom interface and code-generation into a partial class (to avoid manual implementation).

However, IMO a better approach here is to create a secondary DTO class model; that is mutable and which has public properties with get and set. Most serializers will be happy with that, and you can always provide a conversion operator between your DTO model and your primary object model.

like image 148
Marc Gravell Avatar answered Nov 15 '22 00:11

Marc Gravell


My preference is for custom binary serialization, which ensures that you only serialize what you actually need, is the fastest serialization method, and enables you to serialize private members if you really need to. Kevin Marshall has a great serialization comparison post that covers the options and gives performance figures, too: http://blogs.claritycon.com/kevinmarshall/2010/11/03/wp7-serialization-comparison/

like image 26
Derek Lakin Avatar answered Nov 15 '22 00:11

Derek Lakin