1

I recently had a problem concerning serialization of private members of a class. here

The problem was that i tried to serialize private members using XMLSerializer, i also tried the SoapFormatter which couldn't serialize them either. The only reason i wanted to serialize in one of those two formats was that i wanted to be able to check serialized values.

After that, i tried the BinaryFormatter which could serialize private members without any problems.

Why is the BinaryFormatter serializing private members and not the XMLSerializer or the SoapFormatter ?

I'm also wondering, How the BinaryFormatter is able to access the private members of a class?

EDIT

The second question was answered by reflection.

Community
  • 1
  • 1
Irwene
  • 2,807
  • 23
  • 48
  • 1
    How `X` can access private members is almost always answered by "Reflection". Full trust code can access and invoke any private/internal members it wants to. – Damien_The_Unbeliever Jan 09 '14 at 12:01
  • Thank's, seems interesting, i'll look into these mechanism. – Irwene Jan 09 '14 at 13:27
  • 4
    This was just a design choice. BinaryFormatter pulls considerable stunts, it creates an instance of a class without running its constructor. Not something that normal code can do and the core reason you have to use the [Serializable] attribute to give it the okay to do this. Other serializers use the rules. – Hans Passant Jan 09 '14 at 13:41
  • 1
    Thanks guys, too bad you didn't answered would have +1 you. – Irwene Jan 09 '14 at 13:43
  • 2
    I believe that this is done "by design". Purpose of XML is to provide public properties to a different systems. For example, .Net to Java. XML is language of communication between different breeds of frameworks, different companies, etc. Why would you want to serialize private stuff and expose it to the world? But if you want to serialize something that will be used only within your framework, your application, sure - serialize the entire object - no problem. – T.S. Jan 09 '14 at 15:48
  • Oo didn't thought of it this way. Interesting – Irwene Jan 09 '14 at 16:23

0 Answers0