C# Constructor Overload

Description

Constructors follow the same rules for overloading as other methods.

We can provide as many overloads to the constructor as we want, provided they are clearly different in signature.

Syntax

The following code creates two constructors for MyClass.


class MyClass{// w  ww.  j a v  a  2s.co m
     public MyClass()   // zeroparameter constructor 
     { 
        // construction code 
     } 
     public MyClass(int number)   // another overload 
     { 
        // construction code 
     } 
}

Calling Constructors from Other Constructors

A class or struct may overload constructors. To avoid code duplication, one con- structor may call another, using the this keyword:


using System; /*from  w  w  w .j a v  a 2  s.co  m*/

public class Car 
{ 
  public decimal Price; 
  public int Year; 
  public Car (decimal price) { Price = price; } 
  public Car (decimal price, int year) : this (price) { Year = year; } 
} 

When one constructor calls another, the called constructor executes first.

You can pass an expression into another constructor as follows:


public Car (decimal price, DateTime year) : this (price, year.Year) { } 

Example


using System; /*  w w w  .j a va  2 s  .  c  o  m*/
 
class MyClass {  
  public int x;  
  
  public MyClass() { 
    Console.WriteLine("Inside MyClass()."); 
    x = 0; 
  } 
 
  public MyClass(int i) {  
    Console.WriteLine("Inside MyClass(int)."); 
    x = i;  
  } 
 
  public MyClass(double d) { 
    Console.WriteLine("Inside MyClass(double)."); 
    x = (int) d; 
  } 
 
  public MyClass(int i, int j) { 
    Console.WriteLine("Inside MyClass(int, int)."); 
    x = i * j; 
  }    
}    
    
class MainClass {    
  public static void Main() {    
    MyClass t1 = new MyClass();  
    MyClass t2 = new MyClass(88);  
    MyClass t3 = new MyClass(17.23);  
    MyClass t4 = new MyClass(2, 4);  
  
    Console.WriteLine("t1.x: " + t1.x); 
    Console.WriteLine("t2.x: " + t2.x); 
    Console.WriteLine("t3.x: " + t3.x); 
    Console.WriteLine("t4.x: " + t4.x); 
  } 
}

The code above generates the following result.

Example 2

To call its overloaded constructor we can use this.

The following code creates a class Rectangle. In the default constructor we call the Rectangle(int w, int h) by using this(0,0).


using System;//from ww  w.ja v a  2s  .  c o  m

class Rectangle {
   public int Width;
   public int Height;
   
   public Rectangle():this(0,0){
     

   }
   public Rectangle(int w, int h){
      Width = w;
      Height = h;
   }
}
class Program
{
    static void Main(string[] args)
    {
        Rectangle r = new Rectangle();
        Console.WriteLine(r.Width);

        Rectangle r2 = new Rectangle(2, 3);
        Console.WriteLine(r.Width);
    }
}

The output:





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor