Microsoft & .NETVisual BasicWhat Anonymous Methods Might Look Like in VB.NET

What Anonymous Methods Might Look Like in VB.NET

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

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, since VB is getting everything elselike generics and overloaded operatorsI 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.)

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 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 then checkout www.glugnet.org, the web page of the Greater Lansing area Users Group for .NET.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories