Delegates and the VB programmer

When I first started looking at .NET, one of the new concepts that I kept running into was the “delegate” thingies. I kept seeing things written about them, but never walked away really understanding what they were. So it becamse my mission and the first time I really had a “DING!” go off in my head was an explanation in The Book of VB.NET by Matthew MacDonald. Unfortunately, I have long since passed this book on to someone in the user group so I can’t quote it.

Anyway, I thought of this because Avonelle mentioned delegates and the difficulty that she has had getting her head around them and pointed to this article on KnowdotNET that gave her the “aha!” moment.

I actually had a more interesting realization about delegates this summer at TechEd when I was doing a TabletPC Hands on Lab that was all in C#. I couldn’t understand why I had to keep writing so many delegates and then I realized that the delegates were creating event handlers! And THIS is why us VB background people have such a hard time grokking delegates. IN VB (past and .NET), event handlers come free. They are already there. If you drop a control onto a page, then you automatically have access to that controls list of events in your code. If you instantiate a class in your code, the class’s events are available in the dropdown. So we never had to use delegates (not even available to use before .NET anyway) and therefore they didn’t come naturally.

So you C++ and C# developers, next time your walking down the street and you see someone who is scratching their head muttering “delegates…I just don’t get it”, and you are kind enough to attempt to explain and they STILL don’t get it, don’t just shake your head and walk away. You need to relate them to something that already IS in VB so that they have a bridge. Event Handlers are that bridge.

update with just a little more goo: Just an FYI for you VB’ers. I’m working on converting a login form from VB to C# …oh the drudgery of solving casing problems! 🙂  Anyway, I thought I would point out that when you double click on a control to get it’s default event, C# automatically codes up the delegate in the InitializeComponent method. So I clicked on an OK button and not only did I get my event code but it’s delegate was auto generated as well (that’s backwards – because the delegate makes the event handler possible)
  this.btnOK.Click += new System.EventHandler(this.btnOK_Click);

So if you just consider the relationship between this delegate and the familiar event handler

      private void btnOK_Click(object sender, System.EventArgs e){}

it might help a bit…


 

  Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!  

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.