Interface methods in C# define a contract that any implementing class must follow. They are a fundamental concept in object-oriented programming and help in achieving abstraction, modularity, and code reusability.
In C#, an interface can declare methods without providing any implementation (abstract methods). Any class that implements the interface must provide concrete implementations for all interface methods, unless default interface methods are used (C# 8.0+).
public interface IShape { void Draw(); double CalculateArea(); }
public class Circle : IShape { public double Radius { get; set; } public Circle(double radius) { Radius = radius; } // Implementing interface methods public void Draw() { Console.WriteLine("Drawing a Circle with radius " + Radius); } public double CalculateArea() { return Math.PI * Radius * Radius; } }
class Program { static void Main() { IShape shape = new Circle(5); shape.Draw(); Console.WriteLine("Area: " + shape.CalculateArea()); } }
| Benefit | Description |
|---|---|
| Abstraction | Focus on what a class does rather than how it does it. |
| Polymorphism | Enables objects of different classes to be treated as interface types. |
| Maintainability | Allows changes in implementation without affecting dependent code. |
Yes, starting with C# 8.0, interfaces can include default method implementations. Before C# 8.0, interfaces could only declare method signatures.
The compiler will generate an error. A class must implement all interface methods unless it is abstract or the interface provides a default method.
Yes, interface methods can include parameters. The implementing class must provide matching parameters when overriding the method.
Interface methods allow objects of different classes to be used interchangeably through the interface type, enabling flexible and reusable code.
Interface methods involve a slight overhead compared to direct method calls, but they offer more flexibility and abstraction. Performance differences are usually negligible in real-world applications.
Copyrights © 2024 letsupdateskills All rights reserved