What Anonymous Methods Might Look Like in VB.NET

Anonymous methods are similar to C++ inline methods. Basically, an anonymous method is the method body without the method header defined at the point of use. In .NET, anonymous methods are used for delegates. (Think event handlers.)

Thus far, anonymous methods haven't shown up in the current beta version of VB.NET 2.0. However, because VB is getting everything else—like generics and overloaded operators—I suspect anonymous methods are on the way too. This article shows how to define anonymous methods in C# and what they might look like in VB.NET.

Present, Basic Ground Rules

Anonymous methods are at present defined as a block of code, cast to a delegate, and assigned to a delegate. Listing 1 shows what a traditional delegate assignment and definition would look like in C#:

Listing 1: A traditional event handler definition and delegate assignment in a stripped down Windows Forms C# 2.0 sample application

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Anonymous_CSharp
{
   public partial class Form1 : Form
   {
      public Form1()
      {
         InitializeComponent();
      }

      private void Form1_Load(object sender, EventArgs e)
      {
         button1.Click += new EventHandler(ButtonClick);
      }

      private void ButtonClick(object sender, EventArgs e)
      {
         MessageBox.Show("Hello, World!");
      }
   }
}

In VB.NET, you think in terms of event properties, which are the same as delegates. By current definition, you cannot use reference or out arguments in anonymous methods, and they can't contain unsafe code. Thus, if you compile all of these elements (no ref or out arguments, no unsafe code, no method header, casting to a delegate, and assigning to a delegate property), you get the code in Listing 2 (an anonymous method that yields the same result as Listing 1):

Listing 2: Code that behaves identically to Listing 1 but uses an anonymous delegate method

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Anonymous_CSharp
{
   public partial class Form1 : Form
   {
      public Form1()
      {
         InitializeComponent();
      }

      private void Form1_Load(object sender, EventArgs e)
      {
         button1.Click += delegate{ MessageBox.Show("Hello, World!"); };
      }

   }
}

If you compare the code in Listing 1 and Listing 2, you can see the stripped down anonymous method in (bold) in Listing 2. This supposedly enhances code reuse (according to the Visual Studio Beta 2 help), but this claim seems dubious at best. Inline code may traditionally have been slightly optimal, but with modern optimizing compilers even that seems uncertain. Another claim made by the help system is that anonymous methods eliminate the need to declare delegates for custom delegates. This is true, but they eliminate only a single line of code per delegate along with the method header.

Anonymous methods are clever, but they may lead to esoterrorism. While fun, they are probably just clever. (Esoterrorism is the state when code is so esoteric that it spreads fear, panic, and confusion to the maintainer.)

What Anonymous Methods Might Look Like in VB.NET

VB.NET Anonymous Methods

So what might anonymous methods look like in VB.NET? Well, all .NET languages produce CIL (Common Intermediate Language) or MSIL (Microsoft Intermediate Language), which is a derivative of CIL. This means that their results are identical whether the anonymous method comes from C# or VB.NET. The biggest difference between these two languages is really that C# is terse relative to VB's verbosity.

Applying the fact that VB.NET uses words where C# uses symbols, you can take a pretty good guess at VB.NET anonymous methods (see Listing 3).

Listing 3: Anonymous VB.NET methods

Public Class Form1

   Private Sub Form1_Load(ByVal sender As Object, _
      ByVal e As System.EventArgs) Handles Me.Load

      AddHandler Button1.Click, _
         Begin Method
            MsgBox("Hello, World!")
         End Method

   End Sub

End Class

Not very pretty, is it? VB.NET uses the new keyword Operator for overloaded operators, so why not Method for anonymous methods? The anonymous method begins at the Begin Method line and ends at the End Method line.

Maybe the reason anonymous methods aren't in beta 2 is because the VB.NET team can't figure how to make them look better. Making them work should not be a problem, though.

Time Will Tell Soon Enough

VS 2005 is already a great product, but there is a lot of work left to do. The latest news is that it will be released around November 7. As always, it will be interesting to see what is included, what gets left on the cutting room floor, and just how good of a guesser I am.

About the Author

Paul Kimmel is the VB Today columnist for www.codeguru.com and has written several books on object-oriented programming and .NET. Check out his upcoming book UML DeMystified from McGraw-Hill/Osborne (Spring 2005) and Expert One-on-One Visual Studio 2005 from Wrox (Fall 2005). Paul is also the founder and chief architect for Software Conceptions, Inc, founded 1990. He is available to help design and build software worldwide. You may contact him for consulting opportunities or technology questions at pkimmel@softconcepts.com.

If you are interested in joining, sponsoring a meeting, or posting a job, check out www.glugnet.org, the Web page of the Greater Lansing area Users Group for .NET.

Copyright © 2005 by Paul T. Kimmel. All Rights Reserved.



Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds