Thursday, February 10, 2011

Calling Base Class Constructors and Constructor Chaining

C# and Java automatically call base class constructors, and both provide a way to call the constructor of the base class with specific parameters. Similarly both languages enforce that the call to the base class constructor occurs before any initializations in the derived constructor which prevents the derived constructor from using members that are yet to be initialized. The C# syntax for calling the base class constructor is reminiscent of the C++ initializer list syntax.
Both languages also provide a way to call a constructor from another which allows one to reduce the amount of code duplication that can occur in constructors. This practice is typically called constructor chaining.
C# Code

using System;

class MyException: Exception
{

private int Id;

public MyException(string message): this(message, null, 100){ }

public MyException(string message, Exception innerException):
this(message, innerException, 100){ }

public MyException(string message, Exception innerException, int id):
base(message, innerException){

this.Id = id;
}

}

Java Code


class MyException extends Exception{

private int Id;


public MyException(String message){

this(message, null, 100);
}

public MyException(String message, Exception innerException){

this(message, innerException, 100);

}

public MyException( String message,Exception innerException, int id){

super(message, innerException);
this.Id = id;

}
}

No comments:

Post a Comment