This project is read-only.

Deserialization of objects with no parameterless constructor fails



sometimes I simply do not have a possibility to add a parameterless constructor on a class, whose objects i want to deserialize, because they are coming from third party libraries.

Example is DbGeography in System.Data.Spatial.DbGeography in Microsoft's Libs.
I do have a DbGeography property on my object I want to deserialize, but currently I am not able to.

Kind Regards,
Maxim Astafev


maxyha wrote Jun 10, 2014 at 10:28 AM

As hotfix I compiled the code with following addition in Tools.CreateInstance:
            object result = type.IsValueType || type.GetConstructor(Type.EmptyTypes) != null
                ? Activator.CreateInstance(type)
                : System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type);
The FormatServices.GetUninitializedObject(type) does the trick, but as stated in documentation of this method on MSDN, it might be not the best way to achieve this.

From MSDN: "Because the new instance of the object is initialized to zero and no constructors are run, the object might not represent a state that is regarded as valid by that object."