Monday 8 May 2023

Constructor and Deconstructor in C#

 In C#, a constructor is a special method that is called when an instance of a class is created. Its purpose is to initialize the state of the object and allocate any resources needed by the object. 


Here's an example of a simple constructor in C#:


```

public class MyClass

{

    private int _myNumber;


    // Constructor

    public MyClass(int myNumber)

    {

        _myNumber = myNumber;

    }

}

```


In this example, the constructor takes an integer argument and assigns it to a private field called `_myNumber`. When an instance of `MyClass` is created, the constructor is called automatically with the specified argument.


On the other hand, a destructor (also known as a finalizer) is a special method that is called when an object is about to be destroyed, typically to perform cleanup operations and release any resources that the object has acquired during its lifetime. 


Here's an example of a simple destructor in C#:


```

public class MyClass

{

    // Destructor

    ~MyClass()

    {

        // Perform cleanup operations here

    }

}

```


In this example, the destructor is denoted by the `~` character followed by the class name. The body of the destructor can contain any cleanup code that is needed to free resources that were acquired by the object during its lifetime.


Note that in C#, the garbage collector is responsible for automatically freeing up memory that is no longer needed by objects. Therefore, destructors are typically not needed in most C# applications.

No comments:

Post a Comment

Draw Circle in C#

 Here's an example program in C# that uses the `System.Drawing` namespace to draw a circle on a Windows Form: // Mohit Kumar Tyagi using...