Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
using System;
namespace LearnEvents
{
// Defining delegate type (similar to System.EventHandler)
delegate void SomeHandler(object sender, EventArgs e);
class Person
{
// Field-like event declared using keyword 'event'
// allows only for "+=" and "-=" on a hidden instance
// of a delegate of the type SomeHandler.
// Removing 'event' makes this into a field holding
// instance of a delegate.
public event SomeHandler OnSickness;
public Person()
{
// Explicitly creating an instance of a delegate
SomeHandler sicknessHandler =
delegate (object sender, EventArgs e)
{
Console.WriteLine("Person: Vomiting...");
};
// Adding above defined instance to invocation list
OnSickness += sicknessHandler;
}
public void EatTerribleFood()
{
Console.WriteLine("Person: Eating terrible food...");
// Invocation of a sickness event
if (OnSickness != null)
{
OnSickness(this, null);
}
}
}
class Program
{
static void Main(string[] args)
{
var p = new Person();
// adding anonymous method by external to Person code
p.OnSickness += (sender, e) =>
{ Console.WriteLine("External: Calling doctor..."); };
// COMPILATION ERROR
// as long as 'event' was used in first line
// of the Person class. External code cannot invoke sickness.
// Lines below will compile just fine if you remove 'event'
p.OnSickness = (sender, e) =>
{ Console.WriteLine("External: Person feels happy..."); };
p.OnSickness(p, null);
// For neater design it is responsibility of internals
// of the Person class to know when to invoke the event
p.EatTerribleFood();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment