C# Constructors

A Constructor in C# has the same name as the class name. Constructor gets called automatically when we create an object of a class. It does not have a return value. In this lesson, we will learn what are Constructors with examples and how to set parameters.

We have discussed the following topics:

  • How to create a Constructor
  • Constructor Parameters

How to create a Constructor

To create a Constructor in C#, the same class name is used followed by parentheses. Let’s say the class name is Studyopedia, therefore the Constructor would be the following:

Studyopedia() {     // Constructor
   // Code comes here
}

Let us see an example to create a Constructor in C#:

using System;

namespace Demo
{
  class Rectangle
  {  
    // Constructor name is the same as the class name
    Rectangle() {     
      Console.WriteLine("The Constructor!!");
      Console.WriteLine("A rectangle has 4 sides, 4 corners, and 4 right angles");
    }

    static void Main(string[] args)
    {
      /* Constructor gets called automatically when we 
         create an object of a class */
      Rectangle rct = new Rectangle();   
    }
  }
}

Output

The Constructor!!
A rectangle has 4 sides, 4 corners, and 4 right angles

Constructor Parameters

Parameterized Constructor is a constructor with a particular number of parameters. This is useful if you have different objects and you want to provide different values.

Let us see an example of a parameterized constructor with 2 parameters:

using System;

namespace Demo
{
  // Create a Rectangle class
  class Rectangle
  {
     double length;
     double width;
  
    // Constructor name is the same as the class name
    // Constructor Parameters
    Rectangle(double len, double wid) {     
      length = len;
      width = wid;
    }

    static void Main(string[] args)
    {
      /* Constructor gets called automatically when we 
         create an object of a class */
      Rectangle rct1 = new Rectangle(5, 10);   
      Rectangle rct2 = new Rectangle(7, 15);   
      
      // Display
      Console.WriteLine("Area of Rectangle1");
      Console.WriteLine("Length = "+rct1.length+", Width = "+rct1.width);  
      Console.WriteLine("\nArea of Rectangle2");
      Console.WriteLine("Length = "+rct2.length+", Width = "+rct2.width);  
    }
  }
}

Output

Area of Rectangle1
Length = 5, Width = 10

Area of Rectangle2
Length = 7, Width = 15
C# Destructors
C# Classes and Objects
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment