Various places I've been reading have pointed out that on deserialization, the .NET Framework makes a call to FormatterServices.GetUninitializedObject, in which constructors are not called and field initializers are not set. If this is true, why is my constructor being called? Are there instances where constructors and field initializers could be called?
My Class:
[DataContract]
public class TestClass
{
[DataMember]
public string Val1 { get; set; }
[DataMember]
public string Val2 { get; set; }
[DataMember]
public bool NonDefaultBool = true;
private int _nonDefaultInt = 1234;
[DataMember]
public int NonDefaultInt
{
get { return _nonDefaultInt; }
set { _nonDefaultInt = value; }
}
public TestClass()
{
Val1 = "hello";
}
}
My de/serialization code:
var json2 =
@"{
""Val1"":""hello""
}";
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json2)))
{
var thing = DeserializeJsonObject<TestClass>(ms);
Console.WriteLine(GetSerializedData(thing));
}
// ... code left out
protected static TModel DeserializeJsonObject<TModel>(Stream data) where TModel : class
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(TModel));
return jsonSerializer.ReadObject(data) as TModel;
}
static string GetSerializedData<T>(T data)
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T), _knownTypes);
using (MemoryStream ms = new MemoryStream())
{
jsonSerializer.WriteObject(ms, data);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
My output (formatted and commented me):
{
"NonDefaultBool":false, // field initializer not set
"NonDefaultInt":0, // field initializer not set
"Val1":"hello", // constructor called
"Val2":null
}