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.

 

Share your thought