Skip to content

Instantly share code, notes, and snippets.

@nycdotnet
Created May 4, 2015 16:36
Show Gist options
  • Save nycdotnet/f30682947dcee54ad791 to your computer and use it in GitHub Desktop.
Save nycdotnet/f30682947dcee54ad791 to your computer and use it in GitHub Desktop.
C# Parameterized Events via Interfaces example

I took the excellent article The Simplest C# Events Example Imaginable by Todd Wilder, and modified it to work entirely with interfaces using the technique suggested here by Stack Overflow user DELUXEnized, which was to use the Action type. This should work on .NET 3.5 and higher. Paste the C# code into a new console app overwriting the default code in Program.cs that is inside the namespace.

Thanks to all who provided these base suggestions.

// INTERFACES
public interface ITicker
{
event Action<ITicker,ITimeOfTick> Tick;
}
public interface ITimeOfTick
{
DateTime Time { get; set; }
}
// CONCRETE CLASSES
public class TimeOfTick : EventArgs, ITimeOfTick
{
private DateTime TimeNow;
public DateTime Time
{
set
{
TimeNow = value;
}
get
{
return this.TimeNow;
}
}
}
public class Metronome : ITicker
{
public event Action<ITicker, ITimeOfTick> Tick;
public void Start()
{
while (true)
{
System.Threading.Thread.Sleep(3000);
if (Tick != null)
{
ITimeOfTick TOT = new TimeOfTick();
TOT.Time = DateTime.Now;
Tick(this, TOT);
}
}
}
}
public class Listener
{
public void Subscribe(ITicker m)
{
m.Tick += HeardIt;
}
private void HeardIt(ITicker m, ITimeOfTick e)
{
System.Console.WriteLine("HEARD IT AT {0}", e.Time);
}
}
// PROGRAM
class Test
{
static void Main()
{
Metronome m = new Metronome();
Listener l = new Listener();
l.Subscribe(m);
m.Start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment