C# events and functions 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: why events are usefull in c#
using System;
namespace SampleApp {
public delegate string MyDel(string str);
class EventProgram {
event MyDel MyEvent;
public EventProgram() {
this.MyEvent += new MyDel(this.WelcomeUser);
}
public string WelcomeUser(string username) {
return "Welcome " + username;
}
static void Main(string[] args) {
EventProgram obj1 = new EventProgram();
string result = obj1.MyEvent("Tutorials Point");
Console.WriteLine(result);
}
}
}