Event
in C# is based on the mechanism that delegate used to work. Event
is useful for broadcasting information (or message) to and receiving data (or message) from other parts of the program.
Event
allows the program to communicate asynchronously and help us build a more responsive application. Besides, Event
can be switched on and off as needed.
Basic Syntax – Event Handler
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BasicEvents
{
// define the delegate for the event handler
public delegate void myEventHandler(string value);
class EventPublisher
{
private string theVal;
// declare the event
public event myEventHandler valueChanged;
public string Val
{
set
{
this.theVal = value;
// when the value changes, fire the event
this.valueChanged(theVal);
}
}
}
class Program
{
static void Main(string[] args)
{
EventPublisher obj = new EventPublisher();
obj.valueChanged += obj_valueChanged;
string str;
do {
Console.WriteLine("Enter a value: ");
str = Console.ReadLine();
if (!str.Equals("exit")) {
obj.Val = str;
}
} while (!str.Equals("exit"));
Console.WriteLine("Goodbye!");
static void obj_valueChanged(string value)
{
Console.WriteLine("The value changed to {0}", value);
}
}
}
}
The code above is an example of Event Handler in C# programming. The primary purpose of the Event Handler in this code snippet is observing the change of theVal property in EventPublisher
class.
We define the delegate for the event handler by the following line of code, and it looks exactly the same as the delegate declaration.
// define the delegate for the event handler
public delegate void myEventHandler(string value);
Once we declared the delegate for the event handler, we need to declare the event in the designated class as a property. In the code above, we declare the event in EventPublisher
class, and we name it as valueChanged
.
// declare the event
public event myEventHandler valueChanged;
After we declare the event, we need to trigger the event as needed. In the example above, we trigger the event when the value of Val
property changed. In the meantime, we pass in the new value of Val
property as a parameter.
public string Val
{
set
{
this.theVal = value;
// when the value changes, fire the event
// trigger the event
this.valueChanged(theVal);
}
}
Everything is set and we need to switch on the Event
. In the main function of program class, we switch on the event by the following code:
obj.valueChanged += obj_valueChanged;
The obj_valueChanged
is the implementation method of the delegate.
Every time, the obj.Val
changed, we fire the event.
if (!str.Equals("exit")) {
obj.Val = str;
}
Anonymous Event Handler
As mentioned before, Event is based on Delegation in C#; so we can implement the Event by using Anonymous Event Handler.
The amend code snippet:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BasicEvents
{
// define the delegate for the event handler
public delegate void myEventHandler(string value);
class EventPublisher
{
private string theVal;
// declare the event
public event myEventHandler valueChanged;
public string Val
{
set
{
this.theVal = value;
// when the value changes, fire the event
// trigger the event
this.valueChanged(theVal);
}
}
}
class Program
{
static void Main(string[] args)
{
EventPublisher obj = new EventPublisher();
//Anonymous Event Implementation
obj.valueChanged += delegate (string val) {
Console.WriteLine("The value changed to {0}", val);
};
string str;
do {
Console.WriteLine("Enter a value: ");
str = Console.ReadLine();
if (!str.Equals("exit")) {
obj.Val = str;
}
} while (!str.Equals("exit"));
Console.WriteLine("Goodbye!");
}
}
}
As you can see, we delete the static void obj_valueChanged(string value)
function. We switch on and implement the event at the same time via the following code.
//Anonymous Event Implementation
obj.valueChanged += delegate (string val) {
Console.WriteLine("The value changed to {0}", val);
};
.NET Framework Guideline For Defining Event Handlers
The code snippets above are customized Event Handlers, whereas the .NET framework provides us with a predefined event handler for our development as well.
The .NET Framework defines a predefined event handler as a template that you can use to send events using the same format that .NET does. .NET event handlers typically take the form of having two arguments. The first
one is the object where the event originated. The second
is a custom sub-class derived from the .NET event args base-class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChainedEvents
{
class MyClass
{
private string theVal;
// declare the event handle
public event EventHandler<ObjChangeEventArgs> objChanged;
public string Val
{
set
{
this.theVal = value;
// when the value changes, fire the event
this.objChanged(this, new ObjChangeEventArgs() { propChanged = "Val" });
}
}
}
class ObjChangeEventArgs : EventArgs
{
public string propChanged;
}
class Program
{
static void Main(string[] args)
{
// create the test class
MyClass obj = new MyClass();
obj.objChanged += delegate(object sender, ObjChangeEventArgs e) {
Console.WriteLine("{0} had the '{1}' property changed", sender.GetType(), e.propChanged);
};
string str;
do {
Console.WriteLine("Enter a value: ");
str = Console.ReadLine();
if (!str.Equals("exit")) {
obj.Val = str;
}
} while (!str.Equals("exit"));
Console.WriteLine("Goodbye!");
}
}
}
First, We declare the event handler by the following code. We define the event by using the generic syntax of C#, instead of the delegate declaration. The name of the event is objChanged
.
// declare the event handler
public event EventHandler<ObjChangeEventArgs> objChanged;
We declare a custom sub-class derived from the .NET event args base-class. In this case, the name of the class is ObjChangeEventArgs
and it is a subclass of EventArgs
, which is a sub-class derived from the .NET event args base-class.
class ObjChangeEventArgs : EventArgs
{
public string propChanged;
}
We set up the event by the following code. There are two parameters in the implementation. this
refers to the original class, in this case, it is MyClass
. new ObjChangeEventArgs()
refers to the subclass of EventArgs
, which is a sub-class derived from the .NET event args base-class.
// when the value changes, fire the event
this.objChanged(this, new ObjChangeEventArgs() {
propChanged = "Val"
});
After that, we switch on and implement the event by the following code:
obj.objChanged += delegate(object sender, ObjChangeEventArgs e)
{
Console.WriteLine("{0} had the '{1}' property changed", sender.GetType(), e.propChanged);
};
Event
in C# programming is widely used in our development, especially when we are doing the web, UI development. It takes time to sink in, but it is very rewarding in the end. Good Luck.
Monsters of various varieties are present in the recreation. Julee Barnie Allistir
Woh I enjoy your posts, saved to my bookmarks!
Nuevo ranking actualizado de préstamos rápidos por Internet disponible ahora.
I am only writing to make you understand what a remarkable experience our princess undergone viewing your webblog. She picked up such a lot of things, with the inclusion of what it is like to possess an ideal teaching spirit to make the mediocre ones without difficulty master specified tortuous topics. You undoubtedly surpassed readers’ expected results. Thanks for rendering those useful, trustworthy, revealing as well as unique tips on your topic to Sandra.
I am only writing to make you understand what a superb experience our princess undergone viewing yuor web blog. She picked up such a lot of things, with the inclusion of what it is like to possess an ideal teaching style to make the mediocre ones without hassle master specified tricky topics. You undoubtedly surpassed visitors’ expected results. Thanks for showing those valuable, trustworthy, informative and in addition fun tips about this topic to Lizeth.
Thanks for the useful information on credit repair on your web-site. The thing I would offer as advice to people will be to give up a mentality they will buy at this moment and pay back later. As being a society most people tend to repeat this for many factors. This includes family vacations, furniture, plus items we really want to have. However, you must separate a person’s wants from the needs. When you’re working to fix your credit score you really have to make some trade-offs. For example you possibly can shop online to economize or you can click on second hand suppliers instead of highly-priced department stores to get clothing.