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?

user2551229
  • 355
  • 5
  • 13
  • 2
    The CLR can call a protected / private constructor if it wants. You can do the same thing using reflection. – vcsjones Jul 04 '13 at 17:05
  • 1
    Through [Reflection](http://msdn.microsoft.com/en-us/library/ms173183%28v=vs.80%29.aspx) - prepare your mind to be blown : ) – djf Jul 04 '13 at 17:07
  • Are you trying to tell me that using reflection I can use private/protected constructors to make an instance of type which implement ones? – user2551229 Jul 04 '13 at 17:16
  • @djf 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 response – user2551229 Jul 04 '13 at 18:00
  • 1
    @user2551229 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](http://stackoverflow.com/questions/267724/why-xml-serializable-class-need-a-parameterless-constructor), [Why do I need a parameterless constructor?](http://stackoverflow.com/questions/12561333/why-do-i-need-a-parameterless-constructor) – djf Jul 04 '13 at 18:35
  • JSON.NET fails at finding protected constructors. Just try to deserialize a DbUpdateConcurrencyException and it acts like it's missing the required constructor. – Triynko Mar 09 '16 at 19:51

0 Answers0