7.3. Instance constructors

Instance constructors in C# are simply Java constructors. The reason for the name is because there is another group of constructors in C# called static constructors (see section 7.4).

Here is an example of a class with overloaded instance constructors.

 1: using System;
 2:
 3: public class Test{
 4:   public static void Main(){
 5:     Test t1 = new Test();
 6:     Test t2 = new Test("Here is a string");
 7:   }
 8:
 9:   // overloaded instance constructors
10:   public Test(){
11:     Console.WriteLine("Running default constructor");
12:   }
13:   public Test(string i){
14:     Console.WriteLine("Running constructor with param");
15:   }
16: }

Output:

c:\expt>test
Running default constructor
Running constructor with param

Like Java

  • Instance constructors ...

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.