Professional Documents
Culture Documents
5 C Lab06
5 C Lab06
Programming in C#
Lab 06
Objectives:
At the end of this session, you will able to understand:
Create and fire an Event
Subcribing to event
2
C# - Lab 6 – Event and Deletage
class MyClass
{
public void nonStaticMethod()
{
Console.WriteLine("nonStaticMethod");
}
3
C# - Lab 6 – Event and Deletage
functionDelegate += MyClass.staticMethod;
functionDelegate += t.nonStaticMethod;
functionDelegate += MyClass.staticMethod;
functionDelegate();
}
}
class MainClass
{
public static void Add2(ref int x)
{
x += 2;
}
4
C# - Lab 6 – Event and Deletage
int x = 5;
functionDelegate(ref x);
Del1(MyString);
Del2(MyString);
5
C# - Lab 6 – Event and Deletage
}
static int DoSomething(string s)
{
Console.WriteLine("DoSomething");
return 0;
}
static int DoSomething2(string s)
{
Console.WriteLine("DoSomething2");
return 0;
}
class StringOps
{
public static string replaceSpaces(string a)
{
Console.WriteLine("replaceSpaces");
return a;
}
6
C# - Lab 6 – Event and Deletage
class MainClass
{
public static void Main()
{
// Initialize a delegate.
StrMod strOp = new StrMod(StringOps.replaceSpaces);
string str;
}
}
7
C# - Lab 6 – Event and Deletage
Exercise 5: Write a program to create a delegate called OddNumberFinder that displays the odd numbers in
the range of 1 to 50. Create an event called OnOddNumber. This event should be fired every time an odd number
is encountered and it should also display its value.
Step 1: Add a console based project ‘Delegate5’ to the solution
Step 2: Right click on project ‘Delegate5’ -> set as Startup project
Step 3: Rename the class file ‘Program.cs’ to ‘Delegate5.cs’
Step 4: Replace the code in ‘Delegate5.cs’ with the given code
using System;
class Testodd
{
public event OddNumberFinder OnOddNumber;
class ChkOddNumberFinder
{
public void FoundOdd(int odd)
{
Console.WriteLine(odd);
Console.WriteLine("Event Fired...");
}
}
class EventDemo
{
public static void Main()
{
Testodd objOdd = new Testodd();
ChkOddNumberFinder objChkOdd = new ChkOddNumberFinder();
objOdd.OnOddNumber += new OddNumberFinder(objChkOdd.FoundOdd);
objOdd.CountOdd();
}
}
The output of program as following
8
C# - Lab 6 – Event and Deletage
class Counter
{
public event EvenNumberHandler OnEvenNumber;
public Counter()
{
OnEvenNumber = null;
}
public void CountTo100()
{
int CurrentNumber;
class EvenNumberHandlerClass
{
public void EvenNumberFound(int EvenNumber)
{
Console.WriteLine(EvenNumber);
9
C# - Lab 6 – Event and Deletage
}
}
class MainClass
{
public static void Main()
{
Counter MyCounter = new Counter();
EvenNumberHandlerClass MyEvenNumberHandlerClass = new
EvenNumberHandlerClass();
MyCounter.OnEvenNumber += new
EvenNumberHandler(MyEvenNumberHandlerClass.EvenNumberFound);
MyCounter.CountTo100();
}
}
The output of program as following
10
C# - Lab 6 – Event and Deletage
References
1) CD ROM C# Programming, Aptech Education
2) http://www.java2s.com/Tutorial/CSharp/CatalogCSharp.htm
3) MSDN Document
11