Since i am new to c#, would like to know about Interfaces and Delegates in c#, the difference between them and scenarios both these to be used. Please don't provide any links, i would like an explanation in simple words.
An interface is a contract - it defines methods and properties that any implementing class has to have and as such any consumer of the interface will know they exist and can use them.
A delegate is a call back site - it defines a method signature that can invoke any method that has the same signature.
See delegates and interfaces on the C# programming guide.
An example of an interface is the IEnumerable interface. It only has one member defined - GetEnumerator
. Any object that implements this interface will have this method and any code using such an object can call this method.
An example of a delegate is the Predicate<T>
delegate. It is a generic delegate that is defines as following:
public delegate bool Predicate<in T>(T obj);
This means that it takes in any type T and returns a bool
. Any method that takes a single type parameter and returns a bool
is a match for this delegate and can be used with it.
Since delegates are also objects, they can be passed in to functions. So, any function that has a Predicate<T>
delegate can pass in any mathod that matches it. Many of the Linq operators have delegates as parameters. See examples here.
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