Tag Archives: C# constructors

C# Constructor Gotchas Part 2: Singletons and the Sequence of Initialization

One of my favourite questions to ask interviewees is, “What is the order of initialization in a C# class?”

This is part of a series of posts featuring simple but informative code samples.
You can find a bit of background information and a list of the other posts in the series here.

If the question is too ambiguous, then to be more specific: place the following items in a list according to the order in which they are executed during initialization of a class in C#: static and instance class constructors, and static and instance field initializers.

The simple answer, ignoring inheritance, is:

Continue reading C# Constructor Gotchas Part 2: Singletons and the Sequence of Initialization

C# Constructor Gotchas Part 1: Calling virtual methods from a constructor

What could go wrong if we call an overridable method from within a constructor?

If you’ve used static code analysis tools then you may have come across a warning instructing you not to call virtual methods in constructors.
This particular warning is one that should not be ignored, and nor should it be suppressed without good reason. It is of particular relevance to those moving to C# from some other object oriented languages which do not behave in quite the same way (more on that later). Continue reading C# Constructor Gotchas Part 1: Calling virtual methods from a constructor

C# Constructor Gotchas

A series of short posts focusing on some interesting aspects of constructors in C#.

Background:

In my previous employment, I was involved in the selection and interviewing of candidates applying for software developer positions. Although we already had a small set of standard technical questions which were put to each candidate during the interview, I was asked to come up with an additional set which could be given as a short written test.
I began compiling a few basic questions covering some important C# keywords such as new, using, yield, and lock. Although I had enough simple questions to use, I began to wonder whether the questions might only be useful in identifying those who had recently read through their C# textbook to prepare for such a test. Continue reading C# Constructor Gotchas