code_junkie

How does WCF deserialization instantiate objects without calling a constructor?

Nov 11th, 2011
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. [DataContract]
  2. public sealed class CreateMe
  3. {
  4. [DataMember] private readonly string _name;
  5. [DataMember] private readonly int _age;
  6. private readonly bool _wasConstructorCalled;
  7.  
  8. public CreateMe()
  9. {
  10. _wasConstructorCalled = true;
  11. }
  12.  
  13. // ... other members here
  14. }
  15.  
  16. using System;
  17. using System.Reflection;
  18. using System.Runtime.Serialization;
  19.  
  20. namespace NoConstructorThingy
  21. {
  22. class Program
  23. {
  24. static void Main()
  25. {
  26. // does not call ctor
  27. var myClass = (MyClass)FormatterServices.GetUninitializedObject(typeof(MyClass));
  28.  
  29. Console.WriteLine(myClass.One); // writes "0", constructor not called
  30. Console.WriteLine(myClass.Two); // writes "2", field initializers is called
  31. }
  32. }
  33.  
  34. public class MyClass
  35. {
  36. public MyClass()
  37. {
  38. Console.WriteLine("MyClass ctor called.");
  39. One = 1;
  40. }
  41.  
  42. public int One { get; private set; }
  43. public readonly int Two = 2;
  44. }
  45. }
Add Comment
Please, Sign In to add comment