C# orientato agli oggetti

Polymorphism

Polymorphism lets calling code work with an abstraction instead of branching on concrete types.

How it works

Call different implementations through one shared contract.

Each object selects its own override at runtime even though the loop variable uses the common Shape type.

Runnable C# example

C#
Run code →
Program.cs
using System;

abstract class Shape { public abstract double Area(); }
class Circle(double radius) : Shape { public override double Area() => Math.PI * radius * radius; }
class Square(double side) : Shape { public override double Area() => side * side; }

class Program
{
    static void Main()
    {
        Shape[] shapes = { new Circle(2), new Square(3) };
        foreach (Shape shape in shapes) Console.WriteLine($"{shape.Area():F2}");
    }
}
Expected output
12.57
9.00

Practice with the debugger

Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.