O'Reilly logo

From Java to C#: A Developer's Guide by Heng Ngee Mok

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.6. Constructor initializers and constructor chaining

Called 'constructor initializers' in C#, the two keywords this (similar to Java's this) and base (similar to Java's super) allow the programmer to invoke an overloaded constructor in the same class and a constructor in the superclass, respectively.

Like Java

  • You can use this() to call an overloaded constructor in the same class by passing into this() the correct parameters. Instead of a separate this() statement, in C#, the this keyword is used like an extension of the constructor declaration as shown in the example below.

     1: using System;
     2:
     3: public class Test{
     4:   public static void Main(){
     5:     Test t = new Test(0);
     6:   }
     7:
     8:   public Test(int i):this("a string"){ 9: Console.WriteLine("constructor ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required