Pages

Sunday, 28 June 2015

Constructor Initializers

Constructor Initializers

By default, the parameterless constructor of the base class is called when an object is being constructed. But constructors can be overloaded, so a base class might have more than one. If you want your derived class to use a specific base class constructor other than the parameterless constructor, you must specify it in a constructor initializer.

There are two forms of constructor initializers:
  • The first form uses the keyword base and specifies which base class constructor to use.
  • The second form uses the keyword this and specifies which other constructor from this class should be used.

Using base Keyword Form

Use following syntax:
public [Derived Class]([parameter list]) : base([parameter list])
{
 ....
}

Look at following example:
class person
{
 public string firstName;
 public string lastName;
 public ushort age;
 public person(string FirstName,string LastName, ushort Age)
 {
  firstName = FirstName;
  lastName = LastName;
  age = Age;
 }
 .....
}

class employee : person
{
 public string company;

 public employee(string FirstName, string LastName, ushort Age, string Company):base(FirstName,LastName,Age)
 {
  company = Company;
 }
 ....
}

class Program
{
 static void Main(string[] args)
 {
  employee me=new employee("Yang", "Sopiana", 29, "Company.inc");
  ....
 }
}

Using this Keyword Form

The other form of constructor initializer instructs the construction process (actually, the compiler) to use a different constructor from the same class. For example, the following shows a constructor with a single parameter for class MyClass. That single-parameter constructor, however, uses a constructor from the same class, but with two parameters, supplying a default parameter as the second one. See following syntax:
public [Class Name]([parameter list]): this([parameter list])
{ 
 ....
}

Following code snipet show you how to use the syntax:
class person
{
 public string firstName;
 public string lastName;
 public ushort age;
 public person(string FirstName)
 {
  firstName = FirstName;
 }

 public person(string FirstName, string LastName) : this(FirstName)
 {
  lastName = LastName;
 }

 public person(string FirstName, string LastName, ushort Age) : this(FirstName, LastName)
 {
  age = Age;
 }
 ....
}

0 comments:

Post a Comment