There is some magic going on with WCF deserialization. How does it instantiate an instance of the data contract type without calling its constructor?
For example, consider this data contract:
[DataContract] public sealed class CreateMe { [DataMember] private readonly string _name; [DataMember] private readonly int _age; private readonly bool _wasConstructorCalled; public CreateMe() { _wasConstructorCalled = true; } // ... other members here }
When obtaining an instance of this object via DataContractSerializer you will see that the field _wasConstructorCalled is false.
So, how does WCF do this? Is this a technique that others can use too, or is it hidden away from us?
FormatterServices.GetUninitializedObject()will create an instance without calling a constructor. I found this class by using Reflector and digging through some of the core .Net serialization classes.I tested it using the sample code below and it looks like it works great:
http://d3j5vwomefv46c.cloudfront.net/photos/large/687556261.png