Thursday, May 8, 2008

Delegate in C# -Part1

To understand delegate first we look at the syntax then we learn some rules about them finally we see when a delegate can be useful.

What is delegate?
Delegate is a class that it’s objects can call method of other classes or other objects.
In other word first of all delegate is a class and we can create an object from them then put a method address in them ( so they have just addresses of methods) then when we call delegate those methods will be called

Syntax
Delegate has 4 steps:
1- Definition : public delegate void TestCallback();
2- Declaration: Testcallback tc;
3- Instantiation: tc= new Testcallback(Test.f);
4- Call: tc();


The first step of delegate is very important because from definition we can understand which type of methods can be called. Just rewrite definition without delegate word then you will come to this fact that it is like definition of method. Like this:

public void Testcallback();

it means that this delegate can call methods with no input and no output (because of void)

The second step is declaration where you define a variable like the time you define any other variable (there is a reason that I see this as separate step)

The Third step is Instantiation where you create the object. It is important that the constructor of delegate just get an address not anything else. Like a method of class or method of another object. In this step we are telling delegate object this is the method address that I want to call but we do not call that method until next step

In last step we call the delegate then delegate will call the methods that it has (from step3) in previous example actually Test.f will be called.

No comments: