custom serialization - ISerializable and protected/private constructor to deserialization
Asked Answered
G

0

6

I don't understand how it works: when I implement ISerializable interface I have to define protected (unless the class is sealed, in which case the constructor should be marked private) constructor:
protected MyClass(SerializationInfo info, StreamingContext context)
This access modifier makes this constructor unusable for any object in the project so how deserialization succeed?

Gynous answered 4/7, 2013 at 17:2 Comment(6)
The CLR can call a protected / private constructor if it wants. You can do the same thing using reflection.Rosemarie
Through Reflection - prepare your mind to be blown : )Fao
Are you trying to tell me that using reflection I can use private/protected constructors to make an instance of type which implement ones?Gynous
@Fao I'm sorry for bothering you but I'm familiar with Reflection as much as Andrew Troelsen teach my with his book (Pro C# 5.0 And The NET 4.5 Framework) or I've just missed this particular use. Troelsen didn't mention nothing about what is happening behind the scene of deserialzation. I was very curious and that is why I have asked. Thanks for responseGynous
@Gynous the crucial point is that the constructor is parameterless, not that it's protected. During the deserialization of an object, a new instance is created first and then all of its fields are initialized. Have a look at these related questions; Why XML-Serializable class need a parameterless constructor, Why do I need a parameterless constructor?Fao
JSON.NET fails at finding protected constructors. Just try to deserialize a DbUpdateConcurrencyException and it acts like it's missing the required constructor.Bidget

© 2022 - 2024 — McMap. All rights reserved.