Friday, May 9, 2008

Delegate -Part2

Now that we have an understand about the syntax next step is that we need to know some rules about delegate
1- Based on definition we can have different signature of method to assign in delegate
Like:
Public delegate void TestCallback(Person p, int status);
This delegate can accept methods with person and int parameters.
See this example:

Public delegate int Testcallback(int a, int b);
TestCallback tc;
Tc = new TestCallback(Test.f);
int result = tc(5,10);
public class Test
{
Public static int f(int a, intb)
{
Return a*b+b;
}
}

2- The first step of delegation (which is a class definition) will be inside a namespace
3- We always pass address in step 3 of delegate as you can see in last example even delegate seems to accept two parameters we just passed method name since it means it accept methods with two parameters
4- Multiple methods can be assigned to a delegate. It means that a delegate can have more than one method address see this example:
Public delegate void TestCallback();
TestCallback tc;
Tc = new TestCallBack(Test.f);
Tc += new TestCallBack(Test.g);
Tc();
Now when tc is called first f method and then g method will be called
5- Delegate operators are: +, -, +=, -= these operators help you to assign or remove method address from delegate
6- If you closely look into delegate steps what we are doing is that put a method address in delegate then we call delegate to call that method. The question is that why we need that ?Why we don’t call the method directly? Answering to this question is postponed to next lesson of delegate. However, There is a very important point which is we never should use step 3 and step 4 of delegate in one place (like in one method) because we are just wasting our time instead of calling our method we are putting the method in delegate and then we are calling delegate to call the method! We could call the method directly.

1 comment:

Masoud Tabatabaei said...

I 'm really glad to see your weblog Emad.