Showing posts with label Delegate. Show all posts
Showing posts with label Delegate. Show all posts

Friday, May 16, 2008

Sample of Delegate in a web application



You hardly can find a sample of delegate in books. Also in my classes people ask me “Could you give us some real example of delegate?” Ok this is a real sample of delegate that I used for one of my applications:


First let’s understand the application:

The application was a web application. It had a master page with 6 tabs and 3 buttons (Save all, submit data, Exit). Each tab had to show different information so I had 6 pages using this master page. Client asked me to save information when another tab is selected or when they click on save all or submit data (when submit data was selected just application was redirect to another part).Any way my situation was like this some buttons in master page and also in pages I had a save method to save all information about that page. I needed to call save method of the pages when in master page one of those buttons was clicked. Like this:

So I created a saved delegate. In master page I had an instance of this delegate then in button clicks I called that delegate. In each page load I registered the save method into delegate so when in master page saved delegate is called then this save method of page is called actually. Master page does not know what is the method registered in delegate. It is just calling delegate. In fact pages register their own save method in delegate so when delegate is called save method will be called.


Tuesday, May 13, 2008

How to Find an object in a generic List (Delegate sample)

In this lesson I am going to show you more examples about delegate. One of the best example of delegate could be Find method in generic list.
See this code:

public List personlist = new List();
private string searchName;
public void FillList()
{
personlist.Add(new Person("Alex", "Botco", 5));
personlist.Add(new Person("Tai", "Chang", 6));
personlist.Add(new Person("Ehsan", "Parsa", 9));
}
public Person FindPersonbyName(string name)
{
searchName = name;
return personlist.FindLast(new Predicate(this.CheckName));
}
private bool CheckName(Person p)
{
return p.Name == searchName;
}
public Person FindPersonById(int Id)
{
return personlist.FindLast(delegate(Person p) { return p.ID == Id; });
}

In this example as you see first in FillList Method some persons are added to personlist each person has name, family and Id. Now we want to search a person based on Id or name. VS 2005 for its generic list has some methods like Find, FindLast, ... these methods accept a delegate (an address of a method). The delegate definition is implemented by Microsoft which is like this:

public delegate bool Predict (T item);

in our example T is Person. Microsoft is using this delegate (which is a method you will write and assign to this delegate) to Find an Item in list. Since you are writing the logic of this method so you can compare whatever you need in the method assigned to delegate.

If you look at the FindPersonbyName method I created an object of delegate and then I addressed the checkName method. And in CheckName I compared names. The downside of this type of coding is that I had to keep name in another variable (searchName) then in check name I compared the person name with searchName.
Another way to write the code is using delegate keyword inside FindLast method you can see an example of this in FindPersonById in this method instead of creating method and then create an object of delegate an assign that method to delegate we are writing the whole implementation in one line.
The syntax always is like this first delegate keyword then imagine we are writing a method so next step is having a parameter again this parameter is always an instance of object that we have in list. In our example that object is Person. Then in {} we write the code as if we were writing inside a method again always we are using the instance we declared in parameter and then compare one of its properties with other variables. The good point about writing code like this is that we do not need to define extra field like searchName in last methd.

I am going to dedicate this article to my dear friend Jeff.

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

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.

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.