You may have heard of VB11, currently in the VS11 developer preview. It adds two main syntax elements - Iterator functions and Async methods. I don't know much about Async methods yet, but here's a quick Iterator tutorial.
Basically, you put the Iterator keyword before the Function keyword and it becomes an iterator and returns an IEnumerable(Of t). Then, you have some kind of loop, and use the new Yield keyword to "return" a value. For example, this method generates lines from an array of points:
Here's how you might use it:Code:''' <summary> ''' Represents a line. ''' </summary> Private Structure Line Public Start As Point Public [End] As Point Public Function IsVertical() As Boolean Return Me.Start.X = Me.End.X End Function Public Function IsHorizontal() As Boolean Return Me.Start.Y = Me.End.Y End Function Public Function IsEmpty() As Boolean Return Me.IsHorizontal() AndAlso Me.IsVertical() End Function Public Shared Operator =(ByVal a As Line, ByVal b As Line) As Boolean Return a.Start = b.Start AndAlso a.End = b.End End Operator Public Shared Operator <>(ByVal a As Line, ByVal b As Line) As Boolean Return a.Start <> b.Start OrElse a.End <> b.End End Operator End Structure ''' <summary> ''' Gets the lines between each point. ''' </summary> ''' <param name="points">The points for which to create lines.</param> Private Shared Iterator Function Lines(ByVal points As IEnumerable(Of Point)) As IEnumerable(Of Line) Dim last As Point? For Each p As Point In points If last IsNot Nothing Then Yield New Line With { .Start = last.Value, .End = p } last = p Next End Function
Use iterators well - they can be really great sometimes.Code:' Draw a square in a *very* roundabout way :) ' By the way, you can omit types in For Each statements in VB 11: ' v For Each line In Lines({ Point.Empty, New Point(100, 0), New Point(100, 100), New Point(0, 100), Point.Empty }) myGraphics.DrawLine(Pens.Red, line.Start, line.End) Next


Reply With Quote



