I read that you can use interfaces and delegates for the same purpose. Like, you can use delegates instead of interfaces.
Can someone provide an example? I've seen an example in the nutshell book but I fail to remember and wanted to ask away.
Is it possible to provide some sample code? Use case?
Thanks.
If you try to put a delegate in an interface, the compiler says that "interfaces cannot declare types." The Ecma-334 standard (8.9 Interfaces) agrees with the remarks on that page and the compiler. Save this answer.
Delegates can me implemented any number of times. Interface can be implemented only one time. It is used to handling events.
Delegates and Interfaces are two distinct concepts in C#. Interfaces allow to extend some object's functionality, it's a contract between the interface and the object that implements it, while delegates are just safe callbacks, they are a sort of function pointers.
Delegates are faster because they are only a pointer to a method. Interfaces need to use a v-table to then find a delegate; They are equal, but delegates are easier to use.
If your interface has a single method, then it is more convenient to use a delegate.
Compare the following examples:
public interface IOperation
{
int GetResult(int a, int b);
}
public class Addition : IOperation
{
public int GetResult(int a, int b)
{
return a + b;
}
}
public static void Main()
{
IOperation op = new Addition();
Console.WriteLine(op.GetResult(1, 2));
}
// delegate signature.
// it's a bit simpler than the interface
// definition.
public delegate int Operation(int a, int b);
// note that this is only a method.
// it doesn't have to be static, btw.
public static int Addition(int a, int b)
{
return a + b;
}
public static void Main()
{
Operation op = Addition;
Console.WriteLine(op(1, 2));
}
You can see that the delegate version is slightly smaller.
If you combine this with built-in .NET generic delegates (Func<T>
, Action<T>
and similar), and anonymous methods, you can replace this entire code with:
public static void Main()
{
// Func<int,int,int> is a delegate which accepts two
// int parameters and returns int as a result
Func<int, int, int> op = (a, b) => a + b;
Console.WriteLine(op(1, 2));
}
Delegates can be used in the same way as a single-method interface:
interface ICommand
{
void Execute();
}
delegate void Command();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With