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 ...
Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.