Delegates -Single method interfaces

  • Delegates are anonymous one-method interfaces.
  • Lets try to implement a simple program using both delegate and interface
  • For example in this below example – it really doesn’t make sense using interface. So in such case always prefer using delegate.
  • This technique only works as long as you only need to abstract a single method. As soon as your abstraction needs a second method, you will need to introduce a proper interface or, preferably, an abstract base class.

Interface

				
					/*Implementing through iterface....*/

ClassImplementingInterface obj = new ClassImplementingInterface(new StringCalculate());
Console.WriteLine(obj.CalculateFiveTimesLength("Pushpendra"));

public class ClassImplementingInterface
{
    private readonly ICalculate _calculate;
    public ClassImplementingInterface(ICalculate calculate)
    {
        _calculate = calculate;
    }

    public int CalculateFiveTimesLength(string name) => _calculate.FiveTimesLength(name);
}


public class StringCalculate : ICalculate
{
    public int FiveTimesLength(string str) => str.Length * 5;
}

public interface ICalculate
{
    int FiveTimesLength(string message);
}

				
			

Delegate

				
					static string DoStuff(Func<string, int> strategy)
{
    return strategy("Pushpendra").ToString();
}

string result = DoStuff(CalculateFiveTimesLength);
string result1 = DoStuff(s=>s.Length*5);
Console.WriteLine(result);
Console.WriteLine(result1);

int CalculateFiveTimesLength(string s)
{
    return s.Length * 5;
}

				
			

output :- 

50

50

50

Leave a Comment