Sunday, October 7, 2007

Interview Questions: Constructors in C#


A good interview-type question: constructors in C#.


Here's a good one for an interview (whether you're the interviewer or the interviewee):

When declaring a constructor in the subclass, should I explicitly call the base class's constructor?
And if I don't - will the base class's constructor get called anyway?

That's basically what a discussion between my friend Marcin and me got down to...

If you've ever used Resharper (don't tell me you haven't!), you might have noticed that when you go:
class SubClass : BaseClass
{
public SubClass() : base()
{
// some code here
}
}
it will gray out base(), because it is redundant.

And it's true - because if the base constructor wasn't called, the object might not get fully initialized - and that would in a sense break the Liskov's Substitution Principle...

Actually - you do not have to "agree" for the base parameterless constructor to be invoked. You can choose a different one instead:
public SubClass() : base(5)
{
// some code here
}

However - if you look at this summary C# Constructors:
There must always be a "chain" of constructors which runs constructors all the way up the class hierarchy. Every class in the hierarchy will have a constructor invoked, although some of those constructors may not explicitly appear in the code.

All clear now, eh? ;)

No comments: