When to Use Delegates Instead of Interfaces
c#, delegates, interface
Solution
A class may need more than one implementation of the method.
public delegate int PerformCalculation(int x, int y);
void SomeMethod()
{
PerformCalculation PerformCalculation_1 = myDelegateFun_1;
PerformCalculation PerformCalculation_2 = myDelegateFun_2;
PerformCalculation_1(5, 3);
PerformCalculation_2(5, 3);
}
private int myDelegateFun_1(int x, int y)
{
return x + y;
}
private int myDelegateFun_2(int x, int y)
{
return x + y;
}
In the above example PerformCalculation_1, PerformCalculation_2 are multiple implementation of PerformCalculation
A class only needs one implementation of the method
interface IDimensions
{
float Length();
}
class Box : IDimensions
{
float Length()
{
return lengthInches;
}
}
In the above example only single implementation of method exposed by interface.
Problem
According to this article, it says: Use a delegate in the following circumstances: - A class may need more than one implementation of the method. Use an interface in the following circumstances: - A class only needs one implementation of the method. Can someone explain this to me?