What is the default constructor in C#?



A class constructor is a special member function of a class that is executed whenever we create new objects of that class. A default constructor does not have any parameter.

The following is an example showing how to work with default constructor in C# −

Example

 Live Demo

using System; namespace LineApplication {    class Line {       private double length; // Length of a line       public Line(double len) { //Parameterized constructor       Console.WriteLine("Object is being created, length = {0}", len);          length = len;       }       public void setLength( double len ) {          length = len;       }       public double getLength() {          return length;       }       static void Main(string[] args) {          Line line = new Line(10.0);          Console.WriteLine("Length of line : {0}", line.getLength());          // set line length          line.setLength(6.0);          Console.WriteLine("Length of line : {0}", line.getLength());          Console.ReadKey();       }    } }

Output

Object is being created, length = 10 Length of line : 10 Length of line : 6
Updated on: 2020-06-20T12:46:36+05:30

283 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements