C# Constructors And Destructors

C# Code Snippets Constructors And Destructors
Share:

About

In this code snippet, we’ll learn about constructors in C#.

A constructor is a method that gets called when a class is initialized. We can pass arguments into the constructor method and then use them inside the method to initialize the properties of the class. A class can have multiple constructors as they are methods and can thus be overloaded.

A destructor is the opposite of a constructor. It’s a method that gets called just before an instance of a class will get garbage collected(removed from memory) and you can use it to “clean up” by disposing of streams, network connections, unsubscribing from events, etc…

Let’s look at the code example below to see how to implement a constructor.

Code:

using System;

namespace Constructors
{
    class Program
    {
        static void Main(string[] args)
        {
            //Here => MyClass(10) we are calling the constructor method and passing it a parameter(argument). 
            MyClass MC = new MyClass(10); 

            Console.WriteLine(MC.MyProperty);

            Console.ReadLine();
        }
    }

    class MyClass
    {
        //This is how you define a constructor method.
        public MyClass(int setMyProperty) //Gets called when a class is first instantiated.
        {
            //Initializing the property.
            MyProperty = setMyProperty;
        }

        public int MyProperty { get; set; }

        //This is how you define a destructor method.
        ~MyClass() //Gets called when a class is about to be garbage collected(removed from memory).
        {
            //Here you can "clean up" by disposing of streams, network connections, unsubscribing from events, etc...
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger