Jul 12

Back to the basics: Why is my constructor not being called?

Posted in Uncategorized      Comments Off on Back to the basics: Why is my constructor not being called?

When we create a new type and define a constructor, I guess there’s nothing wrong with expecting to see that constructor called whenever a new instance of a type is created. The problem is that there are some cases where that doesn’t happen. For instance, here are two situations where your constructor won’t be called:

  • when you serialize/deserialize an object
  • when you use the MemberwiseClone method

In the past, I’ve already mentioned the serialization gotcha (you can read about it here and here), so in this post, I’ll only be concentrating on the MemberwiseClone method. The MemberwiseClone method is protected and defined by the Object class (which means that it is inherited by all the types). You’ll use this method whenever you want to perform a shallow copy of an instance.

What you must keep in mind is that when you call this method, the constructor of the type that is being duplicated won’t be called. Instead, the method will simply allocate the necessary memory and bit-copy the instance fields to that new allocated memory space.

Since this is a protected method, you’ll only be able to call it from within the text of the class (or from a derived class). This means you’re in control and it shouldn’t really cause the same problems you might get when you use serialization.

And that’s it for now. Stay tuned for more.