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

Published Mon, Jul 12 2010 10:14

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.

Filed under:

Comments

# LA.NET [EN] said on Monday, July 12, 2010 9:35 AM

In the last post , I’ve mentioned constructors…but what is a constructor? The first thing you should

# ASPInsiders said on Monday, July 12, 2010 10:16 AM

In the last post , I’ve mentioned constructors…but what is a constructor? The first thing you should

# LA.NET [PT] said on Wednesday, July 14, 2010 2:46 AM

[Update: updated the text that explains why you’d need to make an explicit call to the base class’ constructor

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above:  

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover