Gate to Delegates in VB.NET
- Arun
Nair, MCSD, MCSE
Visual Basic .NET
has not only extended the versatility of the Visual Basic language but also
harnessed the power of the .NET framework, the new "Delegate" feature
is one of them. So now you don't get the sneer of the self proclaimed C++ or
Java programmers looking down on VB programmers as mere mortals!
More about Delegates, what is the closest you can think of a Delegate? Well
a Delegate is an entity that is entrusted with the task of representation, assign
or passing on information. In code sense, it means a Delegate is entrusted with
a Method to report information back to it when a certain task(which the Method
expects) is accomplished outside the Method's class.
Now does that sound familiar to you? Well, think Event Handlers and you got Delegates into the picture. Let me demystify, when a Mouse move event occurs its the Form_MouseMove method that is invoked. But who does the work of passing the invokation from the event to the method? Its the MouseEventHandler Delegate that is entrusted with representing the Form_MouseMove method and whose job is report back to Form_MouseMove when a MouseMove event occurs. Now delegates are Typesafe which means the Delegate can work with a Method or "callback" only if it has the same signature as the Delegate. Delegates form an integral part of the .NET framework and the more you know the better!
Now that I've hopefully clarified what a Delegate is, lets see an example of a Printer to give you a clearer picture. We'll create a Printer class which has basic attributes like the Name of the Printer and the Ink level in the cartridge. Now the Printer class has a delegate CartridgeEventHandler which is invoked by the InkLevel property when the level of ink in the cartridge passes through certain intervals. The delegate in turn invokes the Method it represents or is entrusted with dutifully passing on information to it.
|
Now lets create
a Windows form which interfaces with the Printer class. The Windows form has
a Status panel which displays the Ink status of the cartridge(Full, Half, Low
and Empty) and a Trackbar. We can decrease/increase the level of ink in the
cartridge using the Trackbar.
|