Constructor Programming Example C#

In this chapter you will understand constructor and destructor with simple programming example

Programming Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace constructor_examples
{
    class ShowMessage
    {
        public ShowMessage()
        {
            Console.WriteLine("Hi, I am default message");
        }

        public ShowMessage(string message)
        {
            Console.WriteLine(message);
        }

        ~ShowMessage()
        {
            Console.WriteLine("I am destructor and I clean the resources and free up memory as soon as program closed");
            Console.ReadLine();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ShowMessage sm = new ShowMessage(); //Default constructor
            ShowMessage sm1 = new ShowMessage("I am parameterized constructor. Press Enter to run Destructor"); //parameterized constructor
            Console.ReadLine();
        }
    }
}

 

Output

Hi, I am default message
I am parameterized constructor. Press Enter to run DestructorI am destructor and I clean the resources and free up memory as soon as program closed __

Summary

In this chapter you have seen a simple programming example of constructors and destructors. In the next chapter, there is some easy questions are waiting for you. You must clear the exercise of constructor and destructor for understanding this topic completely.

More Articles

 

Share your thought



PLEASE DISABLE ADBLOCKER AND SUPPORT US!

Please support us by enabling ads on this page. Refresh

YOU DON'T LIKE ADS, WE ALSO DON'T LIKE ADS!
 
But we have to show ads on our site to keep it free and updated. We have to pay huge server costs, domain costs, CDN Costs, Developer Costs, Electricity and Internet Bill. Your little contribution will encourage us to regularly update this site.