Interface VS Delegate

  • Thread starter Thread starter Phill
  • Start date Start date
P

Phill

When should you use an interface over a delegate?

Like if you have a class that needs to sort various types of objects.
Should it use a delegate to do the sorting or require that the objects
implement a sorting interface?

I read that delegates are smaller and of finer granularity than
interfaces. What does that mean exactly? Does it mean they are more
efficient?

Thanks.
 
Hi there... uhm... there are a couple of things you should be aware of...

Interfaces allow us to extend some object's functionality, it's a contract
between the interface and the object that implements it. It is used to
simulate multiple inheritance in C#. In the other hand, we have delegates...
They're just safe callbacks or function pointers. They allow us to notify
that something has happened (Events). As you can see they're different as
well as their use. In your case I'd recommend you to implement an interface
to the objects you want to sort unless... you want to implement some sort of
quicksort algorithm that has a callback (delegate in .NET) as a parameter.

Regards,
 
One way to look at a delegate is that it's an interface with one method.

If your sorting class needs just one method to determine the order of two
objects, then you can use a delegate for that.

Christian
 
Christian Heide Damm said:
One way to look at a delegate is that it's an interface with one method.

If your sorting class needs just one method to determine the order of two
objects, then you can use a delegate for that.

Indeed, "interface with one method" is how I often think about it too.
There are a few important differences though:

o Delegates can be multi-cast. This allows events to be subscribed to
by multiple delegates, effectively. (This could be done with a list
of interface implementations, of course.)

o You can specify any appropriate method for a delegate - it doesn't
have to use a specific name, unlike interfaces (in C#, anyway)

o The method can be static

o The method can be private
 
Back
Top