Skip to content

Instantly share code, notes, and snippets.

@artronics
Created May 28, 2015 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artronics/0d20f56e202d1c624354 to your computer and use it in GitHub Desktop.
Save artronics/0d20f56e202d1c624354 to your computer and use it in GitHub Desktop.
A simple code to demonstrate how events work on C#. this is based on a great video by Mosh Hamedanian: https://www.youtube.com/watch?v=jQgwEsJISy0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace @event
{
class Program
{
static void Main(string[] args)
{
Video video = new Video { Title = "my video" };
VideoEncoder videoEncoder = new VideoEncoder();
EmailService emailService = new EmailService();
SmsService smsService = new SmsService();
videoEncoder.VideoEncoded += emailService.OnVideoEncoded;
videoEncoder.VideoEncoded += smsService.OnVideoEncoded;
videoEncoder.Encode(video);
}
}
public class Video
{
public string Title { get; set; }
}
public class VideoEventArgs : EventArgs
{
public Video Video { get; set; }
}
public class VideoEncoder
{
public event EventHandler<VideoEventArgs> VideoEncoded;
public void Encode(Video video)
{
Console.WriteLine("Encoding...");
OnVideoEncoded(video);
}
protected virtual void OnVideoEncoded(Video video)
{
if (VideoEncoded != null)
VideoEncoded(this, new VideoEventArgs() { Video = video });
}
}
public class EmailService
{
public void OnVideoEncoded(object source, VideoEventArgs e)
{
Console.WriteLine("Sending Email..." + e.Video.Title);
}
}
public class SmsService
{
public void OnVideoEncoded(object source, VideoEventArgs e)
{
Console.WriteLine("Sending Text Message..." + e.Video.Title);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment