I have searched high and low for documentation on how to use this feature. While the loop I could write would be simple and take no time, I really would like to learn how to use this.
Basically I have a class, say, Widget, with a Save() sub that returns nothing. So:
Dim w as New Widget()
w.Save()
basically saves the widget. Now let’s say I have a generic collection List(Of Widget) name widgetList(Of Widget) and I want to run a Save() on each item in that list. It says I can do a
widgetList.ForEach([enter Action(Of T) here])
….but how in the F does this work??? There is no documentation anywhere on the intrablags. Help would be much much appreciated.
If you’re using VB9 (VS2008) I don’t think you’ll be able to use an anonymous function easily – as far as I’m aware, anonymous functions in VB9 have to be real functions (i.e. they have to return a value) whereas
Action<T>doesn’t return anything. C# 2’s anonymous methods and C# 3’s lambda expressions are more general, which is why you’ll see loads of examples usingList<T>.ForEachfrom C# and very few using VB 🙁You could potentially write a
MakeActionwrapper which takes aFunction<T,TResult>and returns anAction<T>, but I suspect other restrictions on VB9 anonymous functions would make this impractical.The good news is that VB10 has much more anonymous function support. (C#4 and VB10 are gaining each other’s features – I believe MS is trying to go for language parity from now on, to a larger extent than before.)
Until then, to use
List<T>.ForEachyou’ll need to write an appropriateSuband useAddressOfto create a delegate from it. Here’s a small example: