Sunday, May 11, 2008

Delegate -Part3

What is the usage of delegate? If you look into the previous part you will see that delegate can accept address of a method then when we call delegate that method will be called. Why we do not call the method directly? (you can see the clip of this lesson click here)


To answer these questions we need to see some samples of delegate and usage of delegate in .net Framework:
First sample:
namespace DelegateFirstSample
{
public class Test
{
public void f()
{
Console.WriteLine("this is a Test");
}
}
}

Let’s say we need to call a method of a class every 2 seconds and we need this functionality for other classes as well (to make it easier let’s say we need to call that method 2 times)

namespace DelegateFirstSample
{
public class Test
{
public void f()
{
Console.WriteLine("this is a Test");
}
}
}

To achieve our goal we better have a class that get a method and run it 2 times (or each 2 seconds)

namespace DelegateFirstSample
{
public delegate void NoifyCallback();
public class Helper
{
public static void Register(NotifyCallback nc,int num)
{
for (int i = 0; i <> num;i++)
nc();
}

2 comments:

Nahid said...

Dear Emad,
I appreciate your decision about teaching C# online. I was searching for a way to decrease my drawbacks in C# in the coming months, now I think that I've already found it. I'm eagerly waiting for new posts.
By the way I really enjoyed reading your sentences about delegates.

Many Thanks

Emad Yazdanpanah said...

Dear Nahid,

Thank you so much having you in my site means a lot to me. I promise you that you will see very intersting lessons. since I have to write to both professionals and begginers it takes more time!
Cheers