tags:

views:

296

answers:

1

Hi, Am vb.net newbie. This question might be very novice and answered before, but i couldn't find. I was trying the lambda features and got struck here.

 Private Function HigerOrderTest(highFunction as Func(Of Int16,Int16)) As Action(of String)
  Dim sam = highFunction(3)    
  Dim DoIt as Action(of String)
  DoIt = sub(s) console.WriteLine(s)            
    return DoIt  
 End Function

I got "Expression expected." at line DoIt = sub(s) console.WriteLine(s). And when i changed this to DoIt = function(s) console.WriteLine(s) i got Expression does not produce a value. error. Whats the problem?

Cheers

+2  A: 

If you are using Visual Studio 2008 (VB.NET 9), there is a limitation in VB.NET that requires that lambda expressions returns a value, so you cannot use Sub. This has changed in VB.NET 10, so in that environment your code should work as expected.

The problem is that on one hand you need to make your lambda expression into a Function, not a Sub, while on the other hand Console.WriteLine does not have a return value. The solution is to wrap this into a function that calls Console.WriteLine and returns a value:

Private Function ConsoleWriteLine(ByVal text As String) As String
    Console.WriteLine(text)
    Return text
End Function

Then you can use that function in your lambda expression:

Dim DoIt As Action(Of String)
DoIt = Function(s) ConsoleWriteLine(s)
Fredrik Mörk
Yes,AM using VB 9. But i tried with function instead Sub, thats also not working... throws "Expression does not produce a value" error...
Ramesh Vel
@Ramesh: see updated answer
Fredrik Mörk
@Fredrik, i got it now.. thanks.. :)
Ramesh Vel