by luisabreu via LA.NET [EN] on 7/12/2010 9:14:20 AM
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:
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.
Original Post: Back to the basics: Why is my constructor not being called?
The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.