Thursday, December 9, 2010

Delegates in c#

Delegates in c#
Delegate's word meaning is representative. A delegate in .Net is juts like a function pointer in C#.
When we use delegate then there are 3 stages which we need to follow:
Declaration: delegate <returntype> delegateName (<list of arguments>)
Object Creation: delegateName objDelegate = new delegateName(<function to which the delegate points>)
Invoking: objDelegate(<list of arguments that are to be passed to the function>)
The main uses of delegate comes in the following circumstances:
1) When we want to create the controls dynamically, then we cannot create the events for these controls beforehand as these controls are created only on runtime. In that case, if we want to bind these controls with their respective events then we need to use delegate.
So, delegate is first and foremost used for dynamic binding of controls with their events.
2) Delegate is also used in multitasking using threading.
Eg: Suppose we are copying a file from C: drive to D: drive. Then a progress bar would run which would indicate from time to time that how much contents have been copied - like 20% copied, 30% copied. This thing is an example of multiswitching, since here the thread is switching between 2 seperate opertaions. Once it is copying the data from one location to another location and then it is evaluating that how much content has been copied and increasing the progress bar accordingly. But, this switching is happening so fast, that the user gets a feeling as if 2 operations are happenng simultaneously.
So, in the above case, we may use a thread and make it switch between 2 operations. In this case also the delegate comes into play.
A detailed video tutorial has been provided on Delegate's usage for dynamic binding of controls with their events at the below link:
http://visiontechno.net/studymats/delegates.html