Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

C# - Lab 6 – Event and Deletage

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

Part I: Workshop – 15 minutes


Students open workshop in CD ROM, then View, Run, Think about it.

Part II: Step by step – 45 minutes


Exercise 1: Using namespace

Step 1: Open Visual Studio 2005


Step 2: Select the menu File->New->Project to create console based project named ‘SimpleDelegate’ and
Solution named Session05 as following

2
C# - Lab 6 – Event and Deletage

Step 3: Rename the class file ‘program.cs‘ to ‘SimpleDelegate.cs’


Step 4: Replace code in ‘SimpleDelegate.cs’ with given code
using System;

delegate void FunctionToCall();

class MyClass
{
public void nonStaticMethod()
{
Console.WriteLine("nonStaticMethod");
}

public static void staticMethod()


{
Console.WriteLine("staticMethod");
}
}
class MainClass
{
static void Main()
{
MyClass t = new MyClass();
FunctionToCall functionDelegate;
functionDelegate = t.nonStaticMethod;

3
C# - Lab 6 – Event and Deletage

functionDelegate += MyClass.staticMethod;
functionDelegate += t.nonStaticMethod;
functionDelegate += MyClass.staticMethod;

functionDelegate();
}
}

Step 5: Select menu File -> Save to save the file


Step 6: Select Build -> Build ‘SimpleDelegate.cs’ option to build the project
Step 7: Select Debug -> Start without Debuging to execute the program
The output of the program as following

Exercise 2: Delegate with reference parameters

Step 1: Add a console based project ‘Delegate2’ to the solution


Step 2: Right click on project ‘Delegate2’ -> set as Startup project
Step 3: Rename the class file ‘Program.cs’ to ‘Delegate2.cs’
Step 4: Replace the code in ‘Delegate2.cs’ with the given code
using System;

delegate void FunctionToCall(ref int X);

class MainClass
{
public static void Add2(ref int x)
{
x += 2;
}

public static void Add3(ref int x)


{
x += 3;

4
C# - Lab 6 – Event and Deletage

static void Main(string[] args)


{
FunctionToCall functionDelegate = Add2;
functionDelegate += Add3;
functionDelegate += Add2;

int x = 5;
functionDelegate(ref x);

Console.WriteLine("Value: {0}", x);


}
}

Step 5: Select menu File -> Save to save the file


Step 6: Select Build -> Build ‘Delegate2’ option to build the project
Step 7: Select Debug -> Start without Debuging to execute the program
The output of program as following

Exercise 3: Delegate is a function pointer


Step 1: Add a console based project ‘Delegate3’ to the solution
Step 2: Right click on project ‘Delegate3’ -> set as Startup project
Step 3: Rename the class file ‘Program.cs’ to ‘Delegate3.cs’
Step 4: Replace the code in ‘Delegate3.cs’ with the given code
using System;
class MainClass
{
delegate int MyDelegate(string s);
static void Main(string[] args)
{
MyDelegate Del1 = new MyDelegate(DoSomething);
MyDelegate Del2 = new MyDelegate(DoSomething2);

string MyString = "Hello World";

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;
}

Step 5: Select menu File -> Save to save the file


Step 6: Select Build -> Build ‘Delegate3’ option to build the project
Step 7: Select Debug -> Start without Debuging to execute the program
The output of program as following

Exercise 4: Delegates can refer to instance methods

Step 1: Add a console based project ‘Delegate4’ to the solution


Step 2: Right click on project ‘Delegate4’ -> set as Startup project
Step 3: Rename the class file ‘Program.cs’ to ‘Delegate4.cs’
Step 4: Replace the code in ‘Delegate4.cs’ with the given code
using System;

delegate string StrMod(string str);

class StringOps
{
public static string replaceSpaces(string a)
{
Console.WriteLine("replaceSpaces");
return a;
}
6
C# - Lab 6 – Event and Deletage

public static string removeSpaces(string a)


{
Console.WriteLine("removeSpaces");
return a;
}

public static string reverse(string a)


{
Console.WriteLine("reverseSpaces");
return a;
}
}

class MainClass
{
public static void Main()
{

// Initialize a delegate.
StrMod strOp = new StrMod(StringOps.replaceSpaces);
string str;

// Call methods through delegates.


str = strOp("This is a test.");

strOp = new StrMod(StringOps.removeSpaces);


str = strOp("This is a test.");

strOp = new StrMod(StringOps.reverse);


str = strOp("This is a test.");

}
}

Step 5: Select menu File -> Save to save the file


Step 6: Select Build -> Build ‘Delegate4’ option to build the project
Step 7: Select Debug -> Start without Debuging to execute the program
The output of program as following

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;

public delegate void OddNumberFinder(int num);

class Testodd
{
public event OddNumberFinder OnOddNumber;

public void CountOdd()


{
int odd;
for (odd = 1; odd < 50; odd += 2)
OnOddNumber(odd);
}
}

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

Exercise 5: Retrieving Even-Numbered Events

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;

public delegate void EvenNumberHandler(int Number);

class Counter
{
public event EvenNumberHandler OnEvenNumber;

public Counter()
{
OnEvenNumber = null;
}
public void CountTo100()
{
int CurrentNumber;

for (CurrentNumber = 0; CurrentNumber <= 10; CurrentNumber++)


{
if (CurrentNumber % 2 == 0)
{
if (OnEvenNumber != null)
{
OnEvenNumber(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

Part III: Do it yourself – 60 minutes


Exercise 1:
Create a class to monitor and raise events in case of a new employment in your Organization.
Write handlers to add the name of the new employee to the payroll after validating that the name
does not exist. Order the First Day Joining papers for him and send a request to the Administration
department for the id card to be given to the member. If the name does exist on the Payroll, raise
another event to roll back all the activities taken place and ask for a new name to be entered.
Exercise 2:
• In a new source file TestDelegate.cs, declare a delegate type IntAction that has return type void
and takes as argument an int.
• Declare a static method PrintInt that has return type void and takes a single int argument that it
prints on the console.
• Declare a variable act of type IntAction and assign method PrintInt (as a delegate) to that variable.
Call act(42).
• Declare a method static void Perform(IntAction act, int[] arr) { ... } that applies the delegate act to
every element of the array arr.
• Use the foreach statement to implement method Perform. Make an int array arr and call
Perform(PrintInt, arr).

10
C# - Lab 6 – Event and Deletage

Part IV: Homework


Exercise 1: Do assignment of module 13 in CD ROM

References
1) CD ROM C# Programming, Aptech Education
2) http://www.java2s.com/Tutorial/CSharp/CatalogCSharp.htm
3) MSDN Document

11

You might also like