How does DataContractSerializer write to private fields?
Asked Answered
C

2

6

I understand how XMLSerializer could work by using reflection to figure out what public read/write fields or properties it should be using to serialize or de-serialize XML. Yet XMLSerializer requires that the fields be public and read/write.

However, DataContractSerializer is able to read or write to or from completely private fields in a class. So I'm wondering how this is even possible with out explicitly giving DataContractSerializer additional access rights to my class(es).

Cydnus answered 3/4, 2010 at 20:6 Comment(0)
L
7

Reflection has many features. XmlSerializer has, via "sgen.exe" the ability to pre-build the serialization code to a binary (dll). This is useful in some scenarios that don't allow dynamic code, but dlls (just like your code) are limited to the accessible API.

However... reflection isn't this limited, and with enough access you can do pretty much anything. For performance you probably don't want to be using reflection directly a lot, but if you have enough permissions to create IL directly in memory (DynamicMethod), then you can tell it (on a per-dynamic-method basis) which Type the code is associated with. For example, if I create a DynamicMethod passing typeof(Foo) as the owner argument, then that dynamic method has full access to all members (including fields) on Foo. For info, Delegate.CreateDelegate provides similar access to otherwise protected data. Since DataContractSerializer doesn't worry about pre-generation, it can use this access.

Lynch answered 4/4, 2010 at 8:18 Comment(0)
D
2

It does it the same way the XMLSerializer does, by using reflection.

The difference is that XMLSerializer will not touch private fields but the DataContractSerializer will.

See this SO question and answers about reflection and changing of private fields.

Dramaturgy answered 3/4, 2010 at 20:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.