C# constrctor dosn't have to be called

Until a week ago I have a wrong assumption that the constructors are always called, so If I need to initiate services or lists, I intiate them in the constructor and it was called as soon as instance of the class was created.
Today I discover that this assumption is wrong! Constructor not always called and fields "declaration initialization" (IList myList = new List()) doesn't have to be called.

In WCF deserialization (DataContract serialization) the instance constructor is not called.
The Deserialization process use this API
var myClass = (MyClass)FormatterServices.GetUninitializedObject(typeof(MyClass));
 in order to instantiate an instance of the class.
This API allocates space in the heap for the object and return instance of the object withou calling to the constructor neither filed initialization.

If you need to do some init stuff , you should use the 'OnDeserializing' attribute or implement one of the serialization interfaces that give you a callback on serialization/ deserialization events.

I don't love this concept. Object need to have a simple and constant initialization life cycle.

אין תגובות:

הוסף רשומת תגובה