What is Constructors with Example Code

Constructors in object oriented programming are special methods used to initialize objects of a class.
They are called automatically when an object is created.
Constructors have the same name as the class and
can have parameters to initialize object fields.



using System;
 
namespace ConsoleApp1
{
    // Base class
    class Shape
    {
        // Virtual method
        public virtual void Draw()
        {
            Console.WriteLine("Drawing a shape");
 
        }
    }
 
 
 
    // Derived class
    class Circle : Shape
    {
        // Override method
        public override void Draw()
        {
            Console.WriteLine("Drawing a circle");
        }
    }
 
 
 
    // Derived class
    class Rectangle : Shape
    {
        // Override method
        public override void Draw()
        {
           Console.WriteLine("Drawing a rectangle");
        }
    }
 
 
 
    class Program
    {
        static void Main(string[] args)
        {
            // Polymorphic behavior
            Shape[] shapes = new Shape[2];
            shapes[0] = new Circle();
            shapes[1] = new Rectangle();
 
            foreach (Shape shape in shapes)
            {
                shape.Draw(); 

// Calls the appropriate Draw method based on the actual object type
            }
        }
    }
}