Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are Interfaces and Delegates in c#?

Tags:

c#

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.

like image 533
Anuya Avatar asked May 13 '10 07:05

Anuya


1 Answers

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.

like image 146
Oded Avatar answered Oct 19 '22 16:10

Oded