A simple example to show event handling mechanism in C#.
Here We perform addition operation. A new class Addition has been created for this purpose. Class Addition has 2 fields Num1, Num2, and both are integers(as expected).
2 events have been defined,
Add complete event and
Add Failed event
Add complete event, does not take any arguments, while add failed event should respond back with failure and error message
Implementation is rudimentry. My rule is, Num1 and Num2 should not be 0 for successful summation, even if one of them is zero, failure event is raised
program.cs is appended
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
namespace ExRegistryMonitor
{
class Program
{
static void Main(string[] args)
{
Addition add = new Addition(0, 20);
add.addComplete += new EventHandler(add_addComplete);
add.addFailed += new EventHandler(add_addFailed);
int sum = add.Add2Integers();
Console.WriteLine("Sum of 2 numbers :" + sum);
Console.ReadKey(true);
}
static void add_addFailed(object sender, EventArgs e)
{
AdditionEventArgs e1 = (AdditionEventArgs)e;
Console.WriteLine("Failed :" + e1.Message);
}
static void add_addComplete(object sender, EventArgs e)
{
Console.WriteLine("Add completed");
}
}
}
Addition.cs is appended
using System;
using System.Collections.Generic;
using System.Text;
namespace ExRegistryMonitor
{
class Addition : IDisposable
{
#region Addition Members
private int num1;
public int Num1
{
get { return num1; }
set { num1 = value; }
}
private int num2;
public int Num2
{
get { return num2; }
set { num2 = value; }
}
#endregion
#region IDisposable Members
public void Dispose()
{
//do nothing
}
#endregion
#region constructors
public Addition()
{
num1 = num2 = 0;
}
public Addition(int num1)
{
this.num1 = num1;
}
public Addition(int num1, int num2)
{
this.num1 = num1;
this.num2 = num2;
}
#endregion
public event EventHandler addComplete;
public event EventHandler addFailed;
public delegate void sumFailed(object sender, AdditionEventArgs e);
public virtual void OnAddComplete()
{
EventHandler eventHandler = addComplete;
if (addComplete != null)
addComplete(this, null);
}
public virtual void OnAddFailed(object sender, AdditionEventArgs e)
{
EventHandler eventHandler = addFailed;
if (addFailed != null)
addFailed(this, e);
}
public int Add2Integers()
{
int sum = 0;
sum = num1 + num2;
if (num1 == 0 || num2 == 0)
{
AdditionEventArgs e = new AdditionEventArgs();
if (num1 == 0)
e.Message = "NUM1 is 0";
else
e.Message = "NUM2 is 0";
e.Sum = sum;
OnAddFailed(this, e);
return 0;
}
OnAddComplete();
return sum;
}
}
public class AdditionEventArgs : EventArgs
{
private string sMessage;
private int nSum;
public int Sum
{
get { return nSum; }
set { nSum = value; }
}
public string Message
{
get { return sMessage; }
set { sMessage = value; }
}
}
}
No comments:
Post a Comment