Skip to content

Instantly share code, notes, and snippets.

@jyotendra
Created February 7, 2018 09:20
Show Gist options
  • Save jyotendra/f8c0e8c1b194cc65d083acc8d20ca151 to your computer and use it in GitHub Desktop.
Save jyotendra/f8c0e8c1b194cc65d083acc8d20ca151 to your computer and use it in GitHub Desktop.
This describes usage of delegates in C#

Blur filter decalres two methods: -ApplyGaussFilter -ApplyBlur

These methods have following signature: Params => Image, Returns => Image

The FileHandeler class invokes ImageProcessor in which is declared FilterHandler (which is a delegate), to which is attached other methods with same signatures.

Once functions are attached to the delegate - "StartProcessing" method (from ImageProcessor class) is called which runs all the filters attached to the delegate.

using Data.Model;
using System;
using System.Threading;
namespace image.processor
{
class BlurFilter
{
public static Image ApplyBlur (Image img)
{
Console.WriteLine("Applying blur....");
Console.WriteLine("Will be waiting for 3 sec");
Thread.Sleep(3000);
img.IsBlurred = true;
return img;
}
public static Image ApplyGaussFilter (Image img)
{
Console.WriteLine("Applying Gausssian filtering....");
Console.WriteLine("Will be waiting for 5 sec");
Thread.Sleep(5000);
img.IsBlurred = true;
return img;
}
}
class ImageProcessor
{
public delegate Image FilterHandler(Image img);
public Image StartProcessing(Image img, FilterHandler filter)
{
var result = filter(img);
return result;
}
}
}
using Data.Model;
using image.processor;
namespace fileHandeler
{
class FileHandeler
{
public static void GetAndProcessImage()
{
var img = TransferImage();
var imageProcessor = new ImageProcessor();
ImageProcessor.FilterHandler filterHandler = BlurFilter.ApplyBlur;
filterHandler += BlurFilter.ApplyGaussFilter;
imageProcessor.StartProcessing(img, filterHandler);
}
public static Image TransferImage()
{
var image = new Image();
return image;
}
}
}
namespace Data.Model
{
class Image
{
public string Title { get; set; }
public bool IsBlurred { get; set; } = false;
}
}
using System;
using fileHandeler;
namespace test1
{
class Program
{
static void Main(string[] args)
{
FileHandeler.GetAndProcessImage();
Console.WriteLine("Press any key to exit....");
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment