A Delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++. It provides a way which tells which method is to be called when an event is triggered. Example:
CSharp
using System;
class GFG {
public delegate void AddVal( int x, int y);
public void SMeth( int x, int y)
{
Console.WriteLine( "[{0} + {1}] = [{2}]" ,x,y, x + y);
}
public static void Main(String[] args)
{
GFG o = new GFG();
AddVal obj = new AddVal(o.SMeth);
obj(190, 70);
}
}
|
Like a class, Interface can have methods, properties, events, and indexers as its members. But interfaces will contain only the declaration of the members. The implementation of the interface’s members will be given by the class who implements the interface implicitly or explicitly. Example:
CSharp
using System;
interface inter {
void display();
}
class Geeks : inter {
public void display()
{
Console.WriteLine("Welcome to GeeksforGeeks..!");
}
public static void Main(String[] args)
{
Geeks o = new Geeks();
o.display();
}
}
|
Output:
Welcome to GeeksforGeeks..!
Below are some differences between the Delegates and Interfaces in C#:
Delegate | Interface |
---|
It could be a method only. | It contains both methods and properties. |
It can be applied to one method at a time. | If a class implements an interface, then it will implement all the methods related to that interface. |
If a delegate available in your scope you can use it. | Interface is used when your class implements that interface, otherwise not. |
Delegates can me implemented any number of times. | Interface can be implemented only one time. |
It is used to handling events. | It is not used for handling events. |
It can access anonymous methods. | It can not access anonymous methods. |
When you access the method using delegates you do not require any access to the object of the class where the method is defined. | When you access the method you need the object of the class which implemented an interface. |
It does not support inheritance. | It supports inheritance. |
It can wrap static methods and sealed class methods | It does not wrap static methods and sealed class methods.. |
It created at run time. | It created at compile time. |
It can implement any method that provides the same signature with the given delegate. | If the method of interface implemented, then the same name and signature method override. |
It can wrap any method whose signature is similar to the delegate and does not consider which from class it belongs. | A class can implement any number of interfaces, but can only override those methods which belongs to the interfaces. |