Constructor and destructor in C#

Now we are going to learn about constructor and deconstruct in C#.
  • 3462

Introduction

Constructors are same as the class and they support the classes for these modals. constructors are use special syntax. It must compulsory  that constructors must returns something. Mainly a constructor are the special type of the methods. A constructor have no arguments then it is called default arguments. But in some cases we can create the private constructor.
Those constructor which have there argument are called parametrized constructor. A constructor is used when you write code that will be executed when the class instantiated with new keyword.

Example of the Constructor

public struct Point
{
public
int x, y;
public
Point(int x, int y)
{
 this.x = x;
this
.y = y;
}
}
class MainClass
{
public
static void Main()
{
 Point myPoint;
myPoint.x = 10;
myPoint.y = 20;
Console.WriteLine("My Point:");
Console
.WriteLine("x = {0}, y = {1}", myPoint.x, myPoint.y);
Console
.Read();
}
}
}

Destructors

Mainly destructors are used for destroy the unusable memory space. Destructors are the method which is used for clean up the garbage. Basically it is denoted by the ~ sign.

© 2020 DotNetHeaven. All rights reserved.