Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you do inline delegates in vb.net like c#?

Tags:

vb.net

Is it possible to create an inline delegate in vb.net like you can in c#?

For example, I would like to be able to do something inline like this:

myObjects.RemoveAll(delegate (MyObject m) { return m.X >= 10; });

only in VB and without having to do something like this

myObjects.RemoveAll(AddressOf GreaterOrEqaulToTen) 

Private Function GreaterOrEqaulToTen(ByVal m as MyObject)
    If m.x >= 10 Then 
         Return true
    Else
         Return False
    End If
End Function

-- edit -- I should have mentioned that I am still working in .net 2.0 so I won't be able to use lambdas.

like image 713
wusher Avatar asked Dec 09 '08 04:12

wusher


People also ask

What is delegate in VB Net Programming?

Delegates are objects that refer to methods. They are sometimes described as type-safe function pointers because they are similar to function pointers used in other programming languages. But unlike function pointers, Visual Basic delegates are a reference type based on the class System.

What is the difference between lambdas and delegates?

They are actually two very different things. "Delegate" is actually the name for a variable that holds a reference to a method or a lambda, and a lambda is a method without a permanent name. Lambdas are very much like other methods, except for a couple subtle differences.

Is a lambda expression a delegate?

Since a lambda expression is just another way of specifying a delegate, we should be able to rewrite the above sample to use a lambda expression instead of an anonymous delegate. In the preceding example, the lambda expression used is i => i % 2 == 0 . Again, it is just a convenient syntax for using delegates.

What is the purpose of delegate statements in VB net?

The Delegate statement defines the parameter and return types of a delegate class. Any procedure with matching parameters and return types can be used to create an instance of this delegate class. The procedure can then later be invoked by means of the delegate instance, by calling the delegate's Invoke method.


2 Answers

myObjects.RemoveAll(Function(m As MyObject) m.X >= 10)

See Lambda Expressions on MSDN

like image 52
BlackMael Avatar answered Oct 12 '22 01:10

BlackMael


Try:

myObjects.RemoveAll(Function(m) m.X >= 10)

This works in 3.5, not sure about the 2.0 syntax.

like image 25
Shawn Avatar answered Oct 12 '22 01:10

Shawn