polymorphism & Interfaces
Learn polymorphism and interface implementation for flexible and maintainable code. This is a foundational concept in Microsoft application framework that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world .NET experience. Take your time with each section and practice the examples
What is polymorphism?
polymorphism allows objects of different types to be treated as objects of a common base type. It enables one interface to be used for a general class of actions.. This is an essential concept that every .NET developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
interface Implementation
// interface definition
public interface IDrawable
{
void Draw();
double GetArea();
}
// Class implementing interface
public class Circle : IDrawable
{
public double Radius { get; set; }
public Circle(double radius)
{
Radius = radius;
}
public void Draw()
{
Console.WriteLine($"Drawing a circle with radius {Radius}");
}
public double GetArea()
{
return Math.PI * Radius * Radius;
}
}
public class Rectangle : IDrawable
{
public double Width { get; set; }
public double Height { get; set; }
public Rectangle(double width, double height)
{
Width = width;
Height = height;
}
public void Draw()
{
Console.WriteLine($"Drawing a rectangle {Width}x{Height}");
}
public double GetArea()
{
return Width * Height;
}
}
// Using polymorphism
List<IDrawable> shapes = new List<IDrawable>
{
new Circle(5),
new Rectangle(4, 6),
new Circle(3)
};
foreach (IDrawable shape in shapes)
{
shape.Draw();
Console.WriteLine($"Area: {shape.GetArea()}");
}