views:

469

answers:

1

With ASP.NET MVC 1.0, .NET 3.5 and C# you can easily pass a method a lambda expression that will do a "Response.Write" some content when it's executed within the method:

<% Html.SomeExtensionMethod(
    () => { <%
        <p>Some page content<p>
    %> }
) %>

The method signature is similar to this:

public void SomeExtensionMethod(this HtmlHelper helper, Action pageContent)
{
    pageContent();
}

Does anyone know how to peforma a similar call using Lambda expressions in VB.NET using the same method signature shown above?

I've tried the following in VB.NET, but it wont work:

<% Html.SomeExtensionMethod(New Action( _
    Function() %> <p>Some Content</p> <% _
    )) %>

I get an exception saying "Expression Expected."

Can anyone help me with what I'm doing wrong? How do you do this in VB.NET?

+3  A: 

VB.NET 9.0 doesn't support multi-statement lambda expressions or anonymous methods. It also does not support lambda expression that does not return a value meaning that you cannot declare an anonymous function of type Action.

Otherwise this works but is meaningless because the lambda does nothing:

<% Html.SomeExtensionMethod(New Action(Function() "<p>Some Content</p>"))%>

Now let's take your example:

<% Html.SomeExtensionMethod(New Action( _
    Function() %> <p>Some Content</p> <% _
)) %>

Should be translated to something like this:

Html.SomeExtensionMethod(New Action(Function() Html.ViewContext.HttpContext.Response.Write("<p>Some Content</p>")))

which doesn't compile in VB.NET 9.0 because your expression doesn't return a value.

In VB.NET 10 you will be able to use the Sub keyword:

Html.SomeExtensionMethod(New Action(Sub() Html.ViewContext.HttpContext.Response.Write("<p>Some Content</p>")))

which will compile fine.

Darin Dimitrov
What about ASP.NET 4.0?
Chris Pietschmann
this is not true in 3.5 and 4.0. VB has support for lambdas in the newer versions of ASP.NET
Jason
Jason, How do you do this in 3.5 or 4.0?
Chris Pietschmann
Darin, you state that the lambda does nothing in the code you posted. What it does is allow for deferred execution; which can be very handy in some situations.
Chris Pietschmann
@Jason, I didn't say that VB.NET does not support lambda expressions. I say that currently (VB.NET 10) does not support multi-statement lambda expressions.
Darin Dimitrov
A little rectification to my last comment: VB.NET 10 will support multi-line lambda expression. VB.NET 9.0 doesn't.
Darin Dimitrov
It seems that this is one way that C# is superior to VB.NET
Chris Pietschmann
@Chris: As much as i would like to believe you are wrong, i am afraid i have to agree with you on that one. And that is coming from a VB.NET programmer.... :-(
zaladane