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.
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.
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.
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.
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.
myObjects.RemoveAll(Function(m As MyObject) m.X >= 10)
See Lambda Expressions on MSDN
Try:
myObjects.RemoveAll(Function(m) m.X >= 10)
This works in 3.5, not sure about the 2.0 syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With