Uncategorized

[C#] Delegates

What is delegates?

  • A delegate is an object that knows how to call a method or a group of method, or has a reference to functions.
  • A delegate type definds the kind of method that delegate instance can call which are return type and parameter types list.

Example:

delegate int Transformer(int x);
static int Square(int x) => x * x;
Transformer t = Square;
int ans = t(3); //9

Why do we need delegates?

  • For designing extensibility and flexibility
  • In some cases, we have altenative option which is interface.

Example:


var filters = new PhotoFilters();
filters.ApplyBrightness();
filters.Resize();

From the example above, we can see that everytime we want to create a new filter, we have to add code, create that filter, then recompile and redeploy the whole class again. We can use delegate to prevent this.

Example:


public class PhotoProcessor
{
public delegate void PhotoFilterHandler(Photo photo);
public void Process(string path, PhotoFilterHandler filterHandler)
{
filterHandler(photo);
}
}

In Main class:

var processor = new PhotoProcessor();
var filter = new PhotoFilters;
PhotoProcesor.PhotoFilterHandler filterHandler;
filterHandler = filters.ApplyBrightness;
filterHandler += filters.ApplyContrast;
filterHandler += RemoveRedEye;

Special delegates: Action and Func

When to use delegate over interface?

  • Use a delegate when an eventing design pattern in use
  • The caller doesn’t need to access other properties or methods on the object implementing the method.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s