Interfaces define a set of methods that implementing classes must provide. This helps ensure consistency and allows different classes to be used interchangeably if they implement the same interface.
interface IAnimal { void Speak(); } class Dog : IAnimal { public void Speak() { System.Console.WriteLine("Woof"); } } class Cat : IAnimal { public void Speak() { System.Console.WriteLine("Meow"); } } class Program { static void Main() { IAnimal animal = new Dog(); animal.Speak(); animal = new Cat(); animal.Speak(); } }
The variable animal is first assigned a Dog object, so Speak() prints "Woof". Then it is assigned a Cat object, so Speak() prints "Meow".
interface IVehicle { void Drive(); } class Car : IVehicle { // Missing Drive method implementation } class Program { static void Main() { IVehicle v = new Car(); v.Drive(); } }
Classes that implement an interface must provide implementations for all its methods. Missing Drive() causes a compile-time error.
Interfaces declare method signatures without implementation. Option A correctly declares a method without a body. Options A and B provide method bodies, which is invalid in interfaces before C# 8 default implementations. Option A incorrectly uses 'public' modifier inside interface.
interface IShape { double Area(); } class Circle : IShape { public double Radius { get; set; } public Circle(double r) { Radius = r; } public double Area() => 3.14 * Radius * Radius; } class Square : IShape { public double Side { get; set; } public Square(double s) { Side = s; } public double Area() => Side * Side; } class Program { static void Main() { IShape[] shapes = { new Circle(2), new Square(3) }; double totalArea = 0; foreach (var shape in shapes) { totalArea += shape.Area(); } System.Console.WriteLine($"Total area: {totalArea}"); } }
Circle area = 3.14 * 2 * 2 = 12.56
Square area = 3 * 3 = 9
Total = 12.56 + 9 = 21.56