C# Tutorial - Overloading ConstructorsEach 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 ConstructorsA 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 ConstructorsThis 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.
|