C# FAQ: What is the difference between calling base class constructors in CSharp and Java

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

What is the difference between calling base class constructors in C# and Java?

Both the C# and Java languages provide ways to call one constructor from another in a process called constructor chaining. This reduces constructor code duplication.

The following are C# and Java examples of constructor chaining with custom exceptions:

using System; 
 
class CSharpException: Exception
{
   private int errorNumber; 
 
   public CSharpException (string errorMessage): 
      this (errorMessage, null, 99) {}
 
   public CSharpException (string errorMessage, 
      Exception nestedException):
      this(errorMessage, nestedException, 99) {}
 
   public CSharpException (string errorMessage, 
      Exception nestedException, 
      int errorNumber): 
      base (errorMessage, nestedException)
   {
      this.errorNumber = errorNumber;   
   }
 
}
class JavaException extends Exception
{
   private int errorNumber; 
    
   public JavaException (String errorMessage)
   {
      this (errorMessage, null, 99); 
   }
 
   public JavaException (String errorMessage, 
      Exception nestedException)
   {
      this (errorMessage, nestedException, 99); 
   }
 
   public JavaException (String errorMessage,
      Exception nestedException, 
      int errorNumber)
   {
      super (errorMessage, nestedException); 
      this.errorNumber = errorNumber;     
   }
}

See also



Personal tools