7

I am working on some code that was previously written by another developer, and I came across the block of code below:

/// <summary>
/// Default Constructor.
/// </summary>
public Body(Revision parent)
{
  mContainer = parent;
  mSections = new ArrayList();
  mSummary = new ArrayList();
}

/// <summary>
/// Constructs a Body from specified ParseElement.
/// </summary>
/// <param name="parent">Revision container.</param>
/// <param name="elem">Source ParseElement.</param>
public Body(Revision parent, ParseElement elem) : this(parent)
{more constructing stuff}

From what I understand, is that the overloaded constructor would also call the default constructor with the Revision that I send in, causing the initialized ArrayLists to be accessible from the overloaded constructor. Is this correct, or am I totally confused?

Matt
  • 41,216
  • 30
  • 109
  • 147
ploosh
  • 105
  • 1
  • 7

2 Answers2

16

Yes, that is correct. However, to correct your terminology:

  • There is no "default constructor" except possibly the parameterless constructor, which doesn't appear to exist on this class.
  • This has nothing whatsoever to do with inheritance. This technique is actually called constructor chaining.
cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • Also note that the `base` keyword can be used to perform constructor chaining; the difference being that it is used to invoke a constructor in a *base* class, whereas the `this` keyword is used here to invoke a constructor that is declared in *this* class. Also note that specifying neither the `this` keyword nor the `base` keyword is effectively the same as specifying ` : base()`, unless your class does not derive from any base class. If the base class does not define a parameterless constructor, then you will be required to explicitly specify a constructor with the `base` keyword. – Dr. Wily's Apprentice Nov 18 '10 at 21:24
  • @DWA: Except that everything derives from some class, even if it's the implicit superclass `System.Object`. So it would be correct to say that `: base()` is always implicit. ;) – cdhowie Nov 18 '10 at 21:25
  • Ha ha, good point! Although Eric Lippert might disagree with the technical correctness of that statement (http://blogs.msdn.com/b/ericlippert/archive/2009/08/06/not-everything-derives-from-object.aspx), for our purposes (defining classes) you are correct. – Dr. Wily's Apprentice Nov 18 '10 at 21:30
  • Ah, true. Substitute "user-defined types" for "everything" in my comment. :) – cdhowie Nov 18 '10 at 21:35
4

This is correct and the technique is called constructor chaining. In this scenario the this call can be loosely visualized as saying

Run the specified constructor before the current constructor

They both run against the same object instance so changes in the called on are visible in the original.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454