Best practices when using constructors – Redefined

In an older post, I suggested that constructors never should call methods, which possibly can throw exceptions. What also that blog entry explained, is that this idea mainly came from unmanaged languages like C++, where you could easily introduce memory leaks when a constructor throws an exception.

I however came back from that idea, since it also pollutes a lot of your code having to have initialization methods. You add hereby a unspoken contract that, after calling the constructor, you have to call the initialization method in order to use the class properly.

Throw an exception when someone forgets to give a proper argument to your constructor. Use therefore the ArgumentNullException within C#.

Or throw an exception if something internal happens within your constructor. Microsoft even does the same in it’s libraries. Look for example to the FileStream constructor. This one also throws an SecurityException if you don’t have the permissions to create a filestream.

Posted in Best practices, C# by Bruno at December 1st, 2020.

Leave a Reply