c# event delegate code example
Example 1: c# events
class Publisher
{
public delegate void MyEventHandler (object source, EventArgs args);
public event MyEventHandler myEvents;
protected virtual void Method1()
{
if(myEvents != null)
{
myEvents(this, EventArgs.Empty);
}
}
public void Method2()
{
Console.WriteLine("This method is called from the Main function...");
Method1();
}
}
public class Subscriber
{
public void Method1(object source, EventArgs e)
{
Console.WriteLine("The work done by the subscriber after the event was raised...");
}
}
class Program
{
static void Main(string[] args)
{
var myPublisher = new Publisher();
var mySubscriber = new Subscriber();
myPublisher.myEvents += mySubscriber.Method1;
myPublisher.Method2();
}
}
public class MyNewEventArgs : EventArgs
{
public string newData {get; set;}
}
public delegate void EventHandler (object source, MyNewEventArgs args);
myEvents(this, new MyNewEventArgs() { newData = "Hello World!"} );
public void Method1(object source, MyNewEventArgs e)
Example 2: C# delegate
using System;
public class CargoAircraft
{
public delegate void CheckQuantity();
public CheckQuantity ProcessQuantity;
public void ProcessRequirements()
{
ProcessQuantity();
}
}
public class CargoCounter
{
public void CountQuantity() { }
}
class Program
{
static void Main(string[] args)
{
CargoAircraft cargo = new CargoAircraft();
CargoCounter cargoCounter = new CargoCounter();
cargo.ProcessQuantity += cargoCounter.CountQuantity;
cargo.ProcessRequirements();
}
}
}
Example 3: delegate function c#
public delegate void Del(string message);
public static void DelegateMethod(string message)
{
Console.WriteLine(message);
}
Del hadler = DelegateMethod;
hadler("Hello World");
Example 4: delegates and events in c#
public delegate T add<T>(T param1, T param2);
class Program
{
static void Main(string[] args)
{
add<int> sum = Sum;
Console.WriteLine(sum(10, 20));
add<string> con = Concat;
Console.WriteLine(con("Hello ","World!!"));
}
public static int Sum(int val1, int val2)
{
return val1 + val2;
}
public static string Concat(string str1, string str2)
{
return str1 + str2;
}
}