C# Tutorial - Overloading Constructors

posted Jun 26, 2011, 11:14 PM by magic stone

Each class can have more than one constructor, allowing the class to be built taking different information. This can be shown easier with and example. Let us look at the Person class, by making a simple change we can call the parent class constructor through the use of the base keyword.

public Person() : base()
{
  _address = null;
}

If we wanted to create a new Person object by passing a name to it, we can add a second constructor.

public Person( string surname )
{
  _surname = surname;
}

If we wanted to create a new Person object by passing it a date of birth, then we could add a third constructor.

public Person( DateTime dob )
{
  _dateOfBirth = dob;
}

Each of these new constructors can call the default constructor of the Person object, just like calling the base class constructor, but by using the this keyword instead.

public Person( string surname ) : this()
{
  _surname = surname;
}

public Person( DateTime dob ) : this()
{
  _dateOfBirth = dob;
}

Copy Constructors

A great use of overloading the constructor is to create a copy constructor, one that takes a copy of another object of the same type.

public Person( Person p )
{
  this.surname = p.surname;
  . . .
}

Example of Overloading Constructors

This is a great example of overloaded constructors.

public class Loader
{
  public Loader(string fileName, XmlNameTable nameTable)
      :this(new FileStream(fileName,FileMode.Open),nameTable){}
  public Loader(Stream stream, XmlNameTable nameTable)
      :this(new XmlTextReader(stream,nameTable)){}
  public Loader(string fileName):this(fileName, new NameTable()) {}
  public Loader(Stream stream):this(stream,new NameTable()){}
  public Loader(XmlReader xmlReader)
  {
    //actual constructor code goes here
  }
}

There are five constructors here which do different things.

  • If the class is created using the first constructor from the top:

    public Loader(string fileName, XmlNameTable nameTable)

    It makes a call to the next constructor:

    public Loader(Stream stream, XmlNameTable nameTable)

    Which makes a call to the final constructor:

    public Loader(XmlReader xmlReader)
  • If the class is created using the second constructor from the top:

    public Loader(Stream stream)

    A call to the final constructor is made:

    public Loader(XmlReader xmlReader)
  • If the class is created using the third constructor from the top:

    public Loader(string filename)

    A call to the first constructor from the top is made, followed by the first sequence.

  • If the class is created using the fourth constructor from the top:

    public Loader(Stream stream)

    A call to the second constructor from the top is made, followed by the second sequence.

  • If the class is created using the fifth constructor from the top, nothing else is called.


Comments