Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does DataContractSerializer write to private fields?

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).

like image 272
Eric Anastas Avatar asked Apr 03 '10 20:04

Eric Anastas


1 Answers

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.

like image 146
Marc Gravell Avatar answered Sep 27 '22 21:09

Marc Gravell