Interfaces and Delegates:
Aspect |
Interfaces |
Delegates |
Purpose |
Defines a contract that classes must adhere to. |
Represents a method pointer and allows indirect method invocation. |
Implementation |
Defines method signatures, properties, events, or indexers but does not provide implementations. |
Defines a single method signature and does not provide implementations. |
Usage |
Used for defining common behavior among classes, enabling polymorphism, and specifying API contracts. |
Used as callback mechanisms for passing methods as parameters, encapsulating method calls, and handling method references. |
Inheritance |
Supports multiple interface inheritance, allowing a class to implement multiple interfaces. |
N/A |
Example |
public interface IShape
{
double CalculateArea();
}
public class Circle : IShape
{
public double Radius { get; set; }
public double CalculateArea()
{
return Math.PI * Radius * Radius;
}
}
|
public delegate void MyDelegate(string message);
public class MyClass
{
public void ShowMessage(string message)
{
Console.WriteLine(message);
}
}
// Usage:
MyDelegate myDelegate = new MyClass().ShowMessage;
myDelegate("Hello, Delegate!");
|