Ad

Showing how sync events work in c#, not so pratical as in c# 6 and forward is a good practice writing async code.

using System;

namespace delegates
{
	class Program
	{
		static void Main()
		{
		    // Creates a new instance
			Message hi = new Message();
			
			/*
			set the event of the class instance to a 
			lambda expression, beeing an event handler that has the same parameter
			and return type of the delegate in the class instance.
			
			equivalent of creating a new void method with the same
			parameters and seting it to the event in the class instance
			
			*/
			hi.writed += (string hello) =>
			{
			    Console.WriteLine(hello);
			};
			
			// executes the method to validate the event and add it to the delegate
			hi.write = "write property";
		}
	}
	
	public class Message
	{
	    
	    //creates the delegate that will handle the method/ lambda expression/ anonnymous method passed through it
	    public delegate void handler(string hello);
	    
	    //creates the event with the delegate
	    public event handler writed;
	    
	    //method that will check for the event while executing
	    
	    private string _write;
	    public string write
	    {
	        get
	        {
	            return _write;
	        }
	        set
	        {
	            if(value == "write property")
	            {
	               writed?.Invoke("the event was thrown!!!");
	            }
	            
	            Console.WriteLine(value);
	            
	            _write = value;
	        }
	    }
	    
	   //The same as:
	   
	   // public void write(string text)
	   // {
	   //     //you have to check if the event is not null becouse you can't execute a delegates method if it does not exist
	   //     //(the event handler was not set yet)
	   //     if(text == "write method" && writed != null)
	   //     {
	   //         writed("the event was thrown!!!");
	   //     }
	   //     Console.WriteLine(text);
	       
    }
}